Skip to content

Instantly share code, notes, and snippets.

@MaksimDmitriev
Created November 5, 2023 06:24
Show Gist options
  • Save MaksimDmitriev/11b0e010ab4e02c62079af0b912ba705 to your computer and use it in GitHub Desktop.
Save MaksimDmitriev/11b0e010ab4e02c62079af0b912ba705 to your computer and use it in GitHub Desktop.
Quick Sort
package ru.maksim.sample
import org.junit.jupiter.api.Test
class QuickSort {
@Test
fun sample() {
val a = intArrayOf(3, 5, 2, 8, 6, 4)
quickSort(a, 0, a.lastIndex)
}
private fun quickSort(a: IntArray, lo: Int, hi: Int) {
if (hi > lo) {
val p = partition(a, lo, hi)
quickSort(a, lo, p - 1)
quickSort(a, p + 1, hi)
}
}
private fun partition(arr: IntArray, low: Int, high: Int): Int {
// val pivotIndex = (low + high) / 2 // Choose midpoint as the pivot
val pivotIndex = high
val pivot = arr[pivotIndex]
var i = low
var j = high
while (true) {
while (arr[i] < pivot) {
i++
}
while (arr[j] > pivot) {
j--
}
if (i >= j) {
return j // returning i would be incorrect for the input given
}
swap(arr, i, j)
i++
j--
}
}
fun swap(arr: IntArray, i: Int, j: Int) {
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment