選擇排序算法描述:
repeat (numOfElements - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
文字描述:一個元素個數(shù)為n的數(shù)組,循環(huán)n-1次,在循環(huán)中,將未排序元素的第一個元素(為選定的元素)作為最小值,然后對這個元素其后的每一個元素進行遍歷,若某一元素小于那個最小值,則將這一元素設(shè)置為最小值(也就是找出在選定元素之后,且小于選定元素的那一個元素),最后將最小值和選定的元素交換.
void selectionSort(int arr[], int n){
for(int i = 0 ; i < n-1 ; i ++){
// 尋找[i, n)區(qū)間里的最小值
int minIndex = i;
for( int j = i + 1 ; j < n ; j ++ )
if( arr[j] < arr[minIndex] )
minIndex = j;
swap( arr[i] , arr[minIndex] );
}
}
說白了,選擇排序就兩步,遍歷和找最小值
從i = 0遍歷到i = n-2,然后找[i,n)這個區(qū)間的最小值,把這個最小值放到i的位置然后進行下一趟迭代.