let array = [321, 2, 456, 8, 31, 321, 88, 67, 3]
print(array)
func bubbleSort(_ input: Array<Int>) {
guard input.count > 1 else {
print("wrong input")
return
}
var sorted = input
for i in 0..<sorted.count - 1 {
var swaped = true
for j in 0..<sorted.count - i - 1 {
guard swaped else {
print("Bubble sort result: \(sorted)")
return
}
if sorted[j] > sorted[j + 1] {
sorted.swapAt(j, j+1)
swaped = false
}
swaped = true
}
}
print("Bubble sort result: \(sorted)")
}
func insertSort(_ input: Array<Int>) {
guard input.count > 1 else {
print("Wrong input!")
return
}
var sorted = input
for i in 1..<sorted.count {
let value = sorted[i]
for j in (0..<i).reversed(){
if sorted[j] > value {
sorted[j+1] = sorted[j]
}else{
break
}
sorted[j] = value
}
}
print("insert sort result: \(sorted)")
}
func selectSort(_ array: Array<Int>) {
guard array.count > 1 else {
print("Wrong input")
return
}
var sorted = array
for i in 0..<sorted.count {
var targetIndex = i
for j in i..<sorted.count {
if sorted[j] < sorted[targetIndex] {
targetIndex = j
}
}
sorted.swapAt(i, targetIndex)
}
print("select sort result: \(sorted)")
}
bubbleSort(array)
insertSort(array)
selectSort(array)