# Example of Swift implementation of Selection Sort sorting algorithm

- 2020-05-17 06:38:10
- OfStack

Select sort Selection Sort is a sort method similar to insertion sort Insertion Sort, which is also suitable for sorting small collections. Its core idea is to logically divide the sequence into sorted and unsorted parts within the sequence, and constantly find the most consistent elements in the unsorted part and add them to the sorted part, until all the elements in the sequence have been added to the sorted part, and then the whole sequence is sorted.

Bubble sort is a pairwise comparison that is constantly exchanged to achieve the sort, so it is cumbersome.

Selection sort, on the other hand, is choosing the number that you want to swap. This saves a lot of unnecessary steps.

Example implementation of Swift version:

```
func selectSort(var arr: [Int]) ->[Int] {
var min = 0
// Only need to n-1 Trip to
for var i = 0; i < arr.count - 1; ++i {
min = i
// From the first n+1 The beginning of the trip finds the end
for var j = i + 1; j < arr.count; ++j {
// Find a better than min The smaller one, I'll update it 1 The location of the minimum value found
if arr[j] < arr[min] {
min = j
}
}
// if min with i It's not equal. It's a ratio i It's smaller, so it needs to be swapped
if min != i {
let temp = arr[i]
arr[i] = arr[min]
arr[min] = temp
}
}
return arr
}
```