Quick Sort Algorithm

Efficient implementations of Quicksort are not a stable sort, meaning that the relative order of equal sort items is not preserved. develop by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a normally used algorithm for sorting. Robert Sedgewick's Ph.D. thesis in 1975 is considered a milestone in the survey of Quicksort where he resolved many open problems associated to the analysis of various pivot choice schemes including Samplesort, adaptive partitioning by Van Emden as well as derivation of expected number of comparisons and swaps. 

Jon Bentley and Doug McIlroy integrated various improvements for purpose in programming library, including a technique to deal with equal components and a pivot scheme known as pseudomedian of nine, where a sample of nine components is divided into groups of three and then the median of the three medians from three groups is choose. In the Java core library mailing lists, he initiated a discussion claiming his new algorithm to be superior to the runtime library's sorting method, which was at that time based on the widely used and carefully tuned variant of classic Quicksort by Bentley and McIlroy.
package sort

/**
 * This method implements the Quick Sort
 *
 * @param array The array to be sorted
 * It is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.
 *
 * Worst-case performance	    O(n^2)
 * Best-case performance	    O(nLogn)
 * Average performance      	O(nLogn)
 * Worst-case space complexity	O(1)
 **/
fun <T: Comparable<T>> quickSort(array: Array<T>, low: Int, high: Int) {
    if (low < high) {
        val pivot = partition(array, low, high)
        quickSort(array, low, pivot - 1)
        quickSort(array, pivot, high)
    }
}

/**
 * This method finds the pivot index for an array
 *
 * @param array The array to be sorted
 * @param low The first index of the array
 * @param high The last index of the array
 *
 * */
fun <T: Comparable<T>> partition(array: Array<T>, low: Int, high: Int): Int {

    var left = low
    var right = high
    val mid = (left + right) / 2
    val pivot = array[mid]

    while (left <= right) {
        while (array[left] < pivot) {
            left++
        }

        while (array[right] > pivot) {
            right--
        }

        if (left <= right) {
            swapElements(array, left, right)
            left++
            right--
        }
    }
    return left
}

LANGUAGE:

DARK MODE: