lm-tecniche-di-programmazione/src/main/kotlin/it/norangeb/algorithms/sorting/Quicksort.kt

74 lines
2.2 KiB
Kotlin

/*
* MIT License
*
* Copyright (c) 2019 norangebit
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package it.norangeb.algorithms.sorting
object Quicksort : Sorter() {
override fun <T> sort(array: Array<T>, isLess: (T, T) -> Boolean) {
sort(array, 0, array.size - 1, isLess)
}
private fun <T> sort(array: Array<T>, low: Int, high: Int, isLess: (T, T) -> Boolean) {
if (low >= high)
return
val mid = partitioning(array, low, high, isLess)
sort(array, low, mid - 1, isLess)
sort(array, mid + 1, high, isLess)
}
private fun <T> partitioning(
array: Array<T>,
low: Int,
high: Int,
isLess: (T, T) -> Boolean
): Int {
var i = low
var j = high + 1
while (true) {
while (isLess(array[++i], array[low]))
if (i == high) break
while (isLess(array[low], array[--j]))
if (j == low) break
if (i >= j) break
swap(array, i, j)
}
swap(array, low, j)
return j
}
private fun <T> swap(array: Array<T>, i: Int, j: Int) {
val tmp = array[i]
array[i] = array[j]
array[j] = tmp
}
}