Skip to content

Instantly share code, notes, and snippets.

@Alesh17
Last active May 26, 2021 13:51
Show Gist options
  • Select an option

  • Save Alesh17/a6cb93902a096c455a5475e88435daea to your computer and use it in GitHub Desktop.

Select an option

Save Alesh17/a6cb93902a096c455a5475e88435daea to your computer and use it in GitHub Desktop.
fun quickSort(list: MutableList<Int>, min: Int = 0, max: Int = list.size - 1) {

    // завершить выполнение, если длина массива равна 0
    if (list.size == 0) return

    // завершить выполнение если уже нечего делить
    if (min >= max) return

    // выбрать опорный элемент
    val middle: Int = min + (max - min) / 2
    val mainstay: Int = list[middle]

    // разделить на подмассивы, элементы которых больше и меньше опорного элемента
    var i = min
    var j = max

    while (i <= j) {

        while (list[i] < mainstay) i++
        while (list[j] > mainstay) j--

        // меняем местами
        if (i <= j) {
            val temp = list[i]
            list[i] = list[j]
            list[j] = temp
            i++
            j--
        }
    }

    // вызов рекурсии для сортировки левой и правой части
    if (i < max) quickSort(list, i, max)
    if (j > min) quickSort(list, min, j)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment