logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul21/compareSorts.c

/*

This program takes a file full of numbers, reads them into an array,
and then uses one of five sorts (selected by the user) to sort the
numbers. This program's main puropse is to test the performance of 
each sorting algorithm.

Available sorts(from slowest to fastest):
and their big O times. Generally, Quicksort is the fastest of the 
sorting algorithms.

Bubble - Average: O(n^2) Worst: O(n^2)

Selection - Average: O(n^2) Worst O(n^2)

Insertion - Average: O(n^2) Worst O(n^2)

Merge - Average: O(n log n) Worst O(n log n)

Quick - Average: O(n log n) Worst O(n^2)

Rememeber, big O times refer to how changing the input size affects
the runtime of the algorthm. Just because an algorithm has the same
big O time, that does NOT mean they perform the same.


*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sorts.h"

#define LIMIT 1048576

int main(int argc, char *argv[]){

	if(argc < 4){
		fprintf(stderr, "Usage %s <num file>, <number of numbers> <which sort>\n", argv[0]);
		fprintf(stderr, "Currently Supported Sorts: bubble, selection, insertion, merge, quick\n");
		exit(1);
	}

	FILE *fp;

	fp = fopen(argv[1], "r");

	if(fp == NULL){
		fprintf(stderr, "Cannot open file\n");
		exit(-1);
	}

	int sz = atoi(argv[2]);

	if(sz > LIMIT){
		fprintf(stderr, "Too many numbers\n");
		exit(-1);
	}

	int num;
	int nums[sz];
	int i = 0;

	while(fscanf(fp, "%d", &num) == 1){

		nums[i] = num;
		i++;

	}

	/*

	bubble, insertion and selection take in two arguments, 
	the array to be sorted and the size of the array.

	merge and quick take in three arguments, the array to be sorted,
	the beginning index, and the end index. if you want to sort the entire array
	make sure you pass in 0 for the start and sz-1 for the end, 

	*/

	if(strcmp(argv[3], "bubble") == 0){
		bubbleSort(nums, sz);
	}

	if(strcmp(argv[3], "insertion") == 0){
		insertionSort(nums, sz);
	}
	if(strcmp(argv[3], "selection") == 0){
		selectionSort(nums, sz);
	}

	if(strcmp(argv[3], "merge") == 0){
		mergeSort(nums, 0, sz-1);
	}

	if(strcmp(argv[3], "quick") == 0){
		quickSort(nums, 0, sz-1);
	}

	printf("Done");



	return 0;

}