Skip to content

Commit 64c94e3

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

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/main/kotlin/sort/QuickSort.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package sort
2+
3+
/**
4+
* This method implements the Quick Sort
5+
*
6+
* @param array The array to be sorted
7+
* It is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.
8+
*
9+
* Worst-case performance O(n^2)
10+
* Best-case performance O(nLogn)
11+
* Average performance O(nLogn)
12+
* Worst-case space complexity O(1)
13+
**/
14+
fun <T: Comparable<T>> quickSort(array: Array<T>, low: Int, high: Int) {
15+
if (low < high) {
16+
val pivot = partition(array, low, high)
17+
quickSort(array, low, pivot - 1)
18+
quickSort(array, pivot, high)
19+
}
20+
}
21+
22+
/**
23+
* This method finds the pivot index for an array
24+
*
25+
* @param array The array to be sorted
26+
* @param low The first index of the array
27+
* @param high The last index of the array
28+
*
29+
* */
30+
fun <T: Comparable<T>> partition(array: Array<T>, low: Int, high: Int): Int {
31+
32+
var left = low
33+
var right = high
34+
val mid = (left + right) / 2
35+
val pivot = array[mid]
36+
37+
while (left <= right) {
38+
while (array[left] < pivot) {
39+
left++
40+
}
41+
42+
while (array[right] > pivot) {
43+
right--
44+
}
45+
46+
if (left <= right) {
47+
swapElements(array, left, right)
48+
left++
49+
right--
50+
}
51+
}
52+
return left
53+
}
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.assertArrayEquals
4+
import org.junit.Test
5+
6+
class QuickSortTest {
7+
8+
@Test
9+
fun testQuickSort1() {
10+
val array = arrayOf(4, 3, 2, 8, 1)
11+
quickSort(array, 0, array.size - 1)
12+
13+
assertArrayEquals(array, arrayOf(1, 2, 3, 4, 8))
14+
}
15+
16+
@Test
17+
fun testQuickSort2() {
18+
val array = arrayOf("A", "D", "E", "C", "B")
19+
quickSort(array, 0, array.size - 1)
20+
21+
assertArrayEquals(array, arrayOf("A", "B", "C", "D", "E"))
22+
}
23+
24+
@Test
25+
fun testQuickSort3() {
26+
val array = arrayOf(20, 5, 16, -1, 6)
27+
quickSort(array, 0, array.size - 1)
28+
29+
assertArrayEquals(array, arrayOf(-1, 5, 6, 16, 20))
30+
}
31+
}

0 commit comments

Comments
 (0)