C programming (you do not need to write any program)
Please find out the number of comparisons needed for sorting an array of size n from 5 to 40 using Merge Sort. Does it fit the formula seen in the lecture notes?( T (N) = N + N logN) Show your tabulated results and conclusion below:
#include int b[100]; void DoMerging(int a[], int startIndex, int midIndex, int endIndex) { int i, j,k; int l1 = midIndex - startIndex + 1; //take length of first half int l2 = endIndex - midIndex; //length of second half int left[l1], right[l2]; for (i = 0; i < l1; i++) { left[i] = a[startIndex + i]; //copy first half to left array } for (j = 0; j < l2; j++) { right[j] = a[midIndex + 1+ j]; //copy second half to left array } i = 0; j = 0; k = startIndex; //from both left right array copy element to original array //in acsending order while (i < l1 && j < l2) { if (left[i] <= right[j]) { //if left element smaller copy it fist a[k] = left[i]; i++; } else{ //else copy right element a[k] = right[j]; j++; } k++; } //copy remaining element of left array while (i < l1) { a[k] = left[i]; i++; k++; } //copy remaining element of right array while (j < l2) { a[k] = right[j]; j++; k++; } //print the result printf("Merge Result: "); for(k = startIndex; k <= endIndex; k++){ printf("%d ", a[k]); } printf(" "); } void MergeSort(int a[], int startIndex, int endIndex) { // this is the recursive function for MergeSort // we separate the list into two sublists and call mergesort again; // the sublist is marked by startIndex and endIndex int midIndex; if(startIndex < endIndex) { // more than one element, pls sort! midIndex = (startIndex + endIndex) / 2; MergeSort(a, startIndex, midIndex); MergeSort(a, midIndex+1, endIndex); DoMerging(a, startIndex, midIndex, endIndex); } else { // only one element, no need to sort! return; } } int main() { int i; int a[] = { 17, 22, 10, 22, 49, 30, 25, 2 }; printf("Original: "); for(i = 0; i < 8; i++) printf("%d ", a[i]); printf(" "); MergeSort(a, 0, 7); // in the beginning, we put in the whole list, which is from // 0 to 7 printf("Final Result: "); for(i = 0; i < 8; i++) printf("%d ", a[i]); printf(" "); }