Skip to content

Commit 9eb092d

Browse files
bhavyakariavarunu28
authored andcommitted
Added Merge sort
* Added selection sort * Updated SelectionSort according to coding standards. * Changed the incorrect function call in testSelectionSort3. * Added Quicksort. * added description of quick sort. * Added Merge sort.
1 parent 64c94e3 commit 9eb092d

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

src/main/kotlin/sort/MergeSort.kt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package sort
2+
3+
import org.junit.Assert
4+
import org.junit.Test
5+
6+
class MergeSortTest {
7+
8+
@Test
9+
fun testMergeSort1() {
10+
val array = arrayOf(4, 3, 2, 8, 1)
11+
mergeSort(array, 0, array.size - 1)
12+
13+
Assert.assertArrayEquals(array, arrayOf(1, 2, 3, 4, 8))
14+
}
15+
16+
@Test
17+
fun testMergeSort2() {
18+
val array = arrayOf("A", "D", "E", "C", "B")
19+
mergeSort(array, 0, array.size - 1)
20+
21+
Assert.assertArrayEquals(array, arrayOf("A", "B", "C", "D", "E"))
22+
}
23+
24+
@Test
25+
fun testMergeSort3() {
26+
val array = arrayOf(20, 5, 16, -1)
27+
mergeSort(array, 0, array.size - 1)
28+
29+
Assert.assertArrayEquals(array, arrayOf(-1, 5, 16, 20))
30+
}
31+
}

0 commit comments

Comments
 (0)