1+ package sort
2+
3+ /* *
4+ * This function implements Merge Sort
5+ *
6+ * @param array The array to be sorted
7+ * It is a Divide and Conquer algorithm. It sorts the array by dividing it into two halves and comparing the elements.
8+ *
9+ * Worst-case performance O(n log n)
10+ * Best-case performance O(n log n)
11+ * Average performance O(n log n)
12+ * Worst-case space complexity O(n)
13+ */
14+ fun <T : Comparable <T >> mergeSort (array : Array <T >, start : Int , end : Int ) {
15+
16+ val temp = arrayOfNulls<Comparable <* >>(array.size) as Array <T >
17+
18+ if (start < end) {
19+ val mid = start + (end - start) / 2
20+ mergeSort(array, start, mid)
21+ mergeSort(array, mid + 1 , end)
22+ merge(array, temp, start, mid, end)
23+ }
24+ }
25+
26+ /* *
27+ * This function merges the two halves after comparing them
28+ * @param array The array to be sorted
29+ * @param temp The temp array containing the values
30+ * @param start Starting index of the array
31+ * @param mid Middle index of the array
32+ * @param end Ending index of the array
33+ */
34+ fun <T : Comparable <T >> merge (array : Array <T >, temp : Array <T >, start : Int , mid : Int , end : Int ) {
35+
36+ System .arraycopy(array, start, temp, start, end - start + 1 )
37+
38+ var i = start
39+ var j = mid + 1
40+ var k = start
41+
42+ while (i <= mid && j <= end) {
43+ if (temp[i] < temp[j]) {
44+ array[k++ ] = temp[i++ ]
45+ } else {
46+ array[k++ ] = temp[j++ ]
47+ }
48+ }
49+
50+ while (i <= mid) {
51+ array[k++ ] = temp[i++ ]
52+ }
53+
54+ while (j <= end) {
55+ array[k++ ] = temp[j++ ]
56+ }
57+ }
0 commit comments