首页 > 其他 > 详细

Quick Sort

时间:2019-09-30 13:04:54      阅读:86      评论:0      收藏:0      [点我收藏+]
package sort

/**
 * QuckSort best case O(nlgn), worst case O(n^2)
 * worst case occurred in:
 * 1. all element sorted
 * 2. partition unbalanced
 * */
class QuickSort {

    fun sort(array: IntArray): IntArray {
        sortArray(array, 0, array.size - 1)
        printArray(array)
        return array
    }

    private fun printArray(array: IntArray) {
        println("")
        for (item in array) {
            print("$item ,")
        }
    }

    private fun sortArray(array: IntArray, left: Int, right: Int) {
        if (left >= right) {
            return
        }
        val pivotPosition = partition(array, left, right)
        sortArray(array, left, pivotPosition - 1)
        sortArray(array, pivotPosition + 1, right)
    }

    private fun partition(array: IntArray, left: Int, right: Int): Int {
        var i = left
        var j = right
        val pivot = array[j]
        while (i < j) {
            while (i < j && array[i] < pivot) {
                i++
            }
            swap(array, i, j)
            while (i < j && array[j] >= pivot) {
                j--
            }
            swap(array, i, j)
        }
        return i
    }

    private fun swap(array: IntArray, index1: Int, index2: Int) {
        val temp = array[index1]
        array[index1] = array[index2]
        array[index2] = temp
    }
}

 

Quick Sort

原文:https://www.cnblogs.com/johnnyzhao/p/11612076.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!