快排kotlin

fun main() {
    val arr = intArrayOf(4, 3, 7, 2, 5, 1, 6, 9, 3)
    quickSort(arr, { a, b ->
        a - b
    })
    arr.toList().println()
}

fun quickSort(arr: IntArray, comp: (Int, Int) -> Int, left: Int = 0, right: Int = arr.lastIndex) {
    if (left >= right) {
        return
    }
    var i = left
    var j = right
    val pivot = arr[left]
    while (i < j) {
        while (i < j && comp(arr[j], pivot) >= 0) {
            j--
        }
        arr[i] = arr[j]
        while (i < j && comp(arr[i], pivot) <= 0) {
            i++
        }
        arr[j] = arr[i]
    }
    arr[i] = pivot
    quickSort(arr, comp, i - 1)
    quickSort(arr, comp, i + 1, right)
}

你可能感兴趣的:(kotlin,排序算法)