import Foundation
// Extend MutableCollection with a constraints check for Comparable elements
// to provide a reusable, generic in-place sorting method.
extension MutableCollection where Index == Int, Element: Comparable {
/// Sorts the collection in-place in non-decreasing order using Gnome Sort.
///
/// Algorithm Logic (Single Loop):
/// - Advances through the collection 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.
mutating func singleLoopSort() {
var pos = 0
let len = count
while pos < len {
// Move forward if at index 0 or if adjacent pair is in correct order
if pos == 0 || self[pos] >= self[pos - 1] {
pos += 1
} else {
// Swap adjacent out-of-order elements using Swift's built-in swapAt method
swapAt(pos, pos - 1)
pos -= 1
}
}
}
}
/// Main execution entry point.
func main() {
var numbers = [42, -5, 12, 0, 89, -18, 33, 7]
print("Original array:")
print(numbers.map(String.init).joined(separator: " "))
numbers.singleLoopSort()
print("\nSorted array:")
print(numbers.map(String.init).joined(separator: " "))
}
main()
/*
run:
Original array:
42 -5 12 0 89 -18 33 7
Sorted array:
-18 -5 0 7 12 33 42 89
*/