UNIVERSITY OF THE PEOPLE CS3303- 01 PROGRAMMING ASSIGNMENT UNIT 6
My algorithm implements the merge sort algorithm. The merge sort algorithm takes a divide and conquer approach in which a given array is divided into two sub arrays, then each of the sub arrays is sorted in isolation. Afterwards, the two sub arrays are then merged back into one sorted array (GeekforGeeks, n.d). Asymptotic analysis. Generally, the algorithm has a time complexity of O (n log n), but it is prudent to detail the complexities for each step of the main steps in the algorithm. The first stage, which divides the algorithm into two almost equal halves, has a complexity of O(n). The second stage which takes a recursive approach to sort each sub array requires (k log k) time, where k is the size of the sub array. Finally, reuniting the two sub arrays back together would naturally take O(p+q) time. It is also important to note that this algorithm takes a space complexity of O(n) because temporary arrays are required for merging. The merge sort is a superior algorithm to the insertion sort because it requires less exchanges unlike the insertion sort algorithm. To determine the number of swaps, I declared a variable called number_of_swaps, and included it in the merge function. This variable increments itself by one for each swap. I found out that the total number of required exchanges is 68, which is almost half the number of exchanges required by the insertion sort algorithm.
The code: class MergeSort { //the merge sort algorithm uses a divide and conquer approach by sorting dividing //the problem into two halves then sorting each half in isolation //after a successful sort, the two halves are then put back together public static int number_of_swaps = 0; void merge(int arr[], int left, int mid, int right) { // Determine the sizes of the tw0 sub arrays int n1 = mid - left + 1; int n2 = right - mid; // Create temporary arrays int LeftArray[] = new int[n]]; int RightArray [] = new int[n2]; // Copy data to temporary arrays for (int i = 0; i < n1; ++i) LeftArray [i] = arr[left + i]; for (int j = 0; j < n2; ++j) RightArray[ j] = arr[mid + 1 + j]; // Merge the temp arrays // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarray array int k = left; while (i < n1 && j < n2) { if (LeftArray[i] <= RightArray[j]) { arr[k] = LeftArray[i]; i++; } else { arr[k] = RightArray[j]; j++; } k++; number_of_swaps +; } // Copy remaining elements of LeftArray[] if any while (i < n1) { arr[k] = LeftArray[i]; i++; k++; } // Copy remaining elements of RightArray[] if any while (j < n2) { arr[k] = RightArray[j]; j++; k++; } } //The main sorting function