logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/sorts/mergeSort.c

/*

A demonstration of Merge Sort

Merge sort works as follows:

1. Divide the unsorted list into n sublists, each containing 
   one element (a list of one element is considered sorted).

2. Repeatedly merge sublists to produce new sorted sublists 
   until there is only one sublist remaining. This will be the 
   sorted ltst.

The mergeSort function takes in three arguments, the array,
the starting point, and the end point. 


this is just a demonstration file, where you input a number,
and it'll create an array with that many elements, and also
generate that number of random numbers.

*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 1048576

void mergeSort(int arr[], int start, int end);
void merge(int arr[], int start, int mid, int end);

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

	if(argc < 2){
		fprintf(stderr, "Usage: %s <number>\n", argv[0]);
		exit(1);
	}

	int sz = atoi(argv[1]);

	if(sz > MAX || sz < 1){
		fprintf(stderr, "Error: This value is not allowed\n");
		exit(1);
	}

	int arr[sz];
	time_t t;

   /* Intializes random number generator */
	srand((unsigned) time(&t)); //seeding it to the computers clock	

	for(int i = 0; i < sz; i++){
		arr[i] = rand() % sz; //generating an array of random numbers
	}

	mergeSort(arr, 0, sz-1);

	
	return 0;
}



// example of merge sort in C/C++
// merge function takes two intervals
// one from start to mid
// second from mid+1, to end
// and merge them in sorted order

void merge(int arr[], int start, int mid, int end) {
	// create a temp array
	int temp[end - start + 1];

	// crawlers for both intervals and for temp
	int i = start, j = mid+1, k = 0;

	// traverse both arrays and in each iteration add smaller of both elements in temp 
	while(i <= mid && j <= end) {
		if(arr[i] <= arr[j]) {
			temp[k] = arr[i];
			k += 1; i += 1;
		}
		else {
			temp[k] = arr[j];
			k += 1; j += 1;
		}
	}

	// add elements left in the first interval 
	while(i <= mid) {
		temp[k] = arr[i];
		k += 1; i += 1;
	}

	// add elements left in the second interval 
	while(j <= end) {
		temp[k] = arr[j];
		k += 1; j += 1;
	}

	// copy temp to original interval
	for(i = start; i <= end; i += 1) {
		arr[i] = temp[i - start];
	}
}

// arr is an array of integer type
// start and end are the starting and ending index of current interval of arr

void mergeSort(int arr[], int start, int end) {

	if(start < end) {
		int mid = (start + end) / 2;
		mergeSort(arr, start, mid);
		mergeSort(arr, mid+1, end);
		merge(arr, start, mid, end);
	}
}