選擇排序(Selection Sort)是一種非常簡單的排序算法,它將待排序序列劃分成兩部分:已排序部分和待排序部分。起始時,已排序部分爲空,待排序部分爲整個輸入序列。算法會不斷的遍歷待排序部分,找出最小的(或最大的)元素,與待排序序列的最左邊的元素交換,交換後,把左邊的那個元素歸入已排序部分。因爲每次總是從待排序部分中選擇最小(大)的元素,然後歸入已排序部分的末尾,所以最終會得到輸入序列的一個完整有序序列。
例如對輸入數組arr[]=64 25 12 22 11,應用選擇排序算法過程如下
arr[] = 64 25 12 22 11
// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64
// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64
// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64
// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64
C實現
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
fo