/**
* Swaps two elements in an IntArray at the specified indices.
*/
private fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
/**
* Sorts an IntArray in-place in non-decreasing order using Gnome Sort.
*
* Algorithm Logic (Single Loop):
* - Advances through the array using a single while loop index.
* - Moves forward when adjacent elements are in correct relative order.
* - When an out-of-order adjacent pair is encountered, swaps the elements
* and steps backward one index to verify order against preceding items.
* - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
* - Space Complexity: O(1) auxiliary space.
*
* @receiver IntArray to be sorted in place.
*/
fun IntArray.singleLoopSort() {
var pos = 0
val len = this.size
while (pos < len) {
// Move forward if at index 0 or if adjacent pair is in correct order
if (pos == 0 || this[pos] >= this[pos - 1]) {
pos++
} else {
// Swap out-of-order elements in place and step backward
swap(pos, pos - 1)
pos--
}
}
}
/**
* Main application entry point
*/
fun main() {
val numbers = intArrayOf(42, -5, 12, 0, 89, -18, 33, 7)
println("Original array:")
println(numbers.joinToString(" "))
numbers.singleLoopSort()
println("\nSorted array:")
println(numbers.joinToString(" "))
}
/*
run:
Original array:
42 -5 12 0 89 -18 33 7
Sorted array:
-18 -5 0 7 12 33 42 89
*/