zoukankan      html  css  js  c++  java
  • QuickSort


    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 } }

     quicksort是一个comparison-based的排序算法(heap sort,merge sort,插入都是)

  • 相关阅读:
    字符串方法
    函数的属性和方法
    数组的去重!!
    常见的数组方法
    JS中的函数
    JavaScript 中表达式和语句的区别
    运算符优先级
    题解 CF813B 【The Golden Age】
    题解 CF834B 【The Festive Evening】
    题解 CF810B 【Summer sell-off】
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/11612076.html
Copyright © 2011-2022 走看看