Bubble
repeatedly compares adjacent elements and swaps them if they are in the wrong order, until no swaps are required.
func bubbleSort(_ array: inout [Int]) {
let n = array.count
for i in 0..<(n-1) {
for j in 0..<(n-i-1) {
if array[j] > array[j+1] {
array.swapAt(j, j+1)
}
}
}
}
Selection sort
sorts an array by repeatedly finding the minimum element from the unsorted part of the array and putting it at the beginning
func selectionSort(_ array: inout [Int]) {
let n = array.count
for i in 0..<n {
var minIndex = i
for j in (i+1)..<n {
if array[j] < array[minIndex] {
minIndex = j
}
}
array.swapAt(i, minIndex)
}
}
Insertion sort
sorts an array by iteratively inserting an element from the unsorted part of the array into its correct position in the sorted part of the array
func insertionSort(_ array: inout [Int]) {
let n = array.count
for i in 1..<n {
let key = array[i]
var j = i - 1
while j >= 0 && array[j] > key {
array[j+1] = array[j]
j -= 1
}
array[j+1] = key
}
}
Merge sort
divides the array into two halves, sorts each half separately using recursive calls to the same algorithm, and then merges the two sorted halves.
func mergeSort(_ array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let mid = array.count / 2
let left = mergeSort(Array(array[..<mid]))
let right = mergeSort(Array(array[mid...]))
return merge(left, right)
}
func merge(_ left: [Int], _ right: [Int]) -> [Int] {
var mergedArray: [Int] = []
var leftIndex = 0
var rightIndex = 0
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] < right[rightIndex] {
mergedArray.append(left[leftIndex])
leftIndex += 1
} else {
mergedArray.append(right[rightIndex])
rightIndex += 1
}
}
if leftIndex < left.count {
mergedArray.append(contentsOf: left[leftIndex...])
}
if rightIndex < right.count {
mergedArray.append(contentsOf: right[rightIndex...])
}
}