考虑以下代码:
#include <iostream>
using namespace std;
// Exchanges two values in array arr, specified by indices i and j
void exchange(int arr[], int i, int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
// Prints an array arr of length len
void print_array(int arr[], int len)
{
for(int i=0; i<len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
// Finds the index of the minimum value in array arr of length len between indices
// init and the last element (len-1)
int find_min(int arr[], int len, int init)
{
int index = init;
for(int i = init; i < len; i++)
{
if(arr[index] > arr[i])
{
index = i;
}
}
return index;
}
// Sort the array using the selection sort algorithm
void selection_sort(int arr[], int len)
{
int loc;
// We don't need the last iteration when there is only a single element left
for(int pos = 0; pos < (len-1); pos++)
{
cout << "Before iteration " << pos << " array is: ";
print_array(arr, len);
loc = find_min(arr, len, pos);
cout << " Minimum between indices " << pos << " and " << (len-1) << " is: ";
cout << arr[loc] << " at index " << loc << endl;
if (loc != pos)
{
cout << " Exchanging indices " << loc << " and " << pos << endl;
exchange(arr, pos, loc);
}
else
{
cout << " No exchange necessary this iteration. " << endl;
}
cout << "After iteration " << pos << " array is: ";
print_array(arr, len);
// Print an extra line newline, space things out a bit
cout << endl;
}
}
int main(void)
{
int arr[] = {2,6,7,3,1,8};
selection_sort(arr, 6);
}
输出:
迭代前 0 数组为:2 6 7 3 1 8
索引 0 和 5 之间的最小值是:索引 4 处的 1
交换索引 4 和 0
迭代后 0 数组为:1 6 7 3 2 8
迭代前 1 数组为: 1 6 7 3 2 8
索引 1 和 5 之间的最小值是:索引 4 处的 2
交换索引 4 和 1
迭代后 1 数组为: 1 2 7 3 6 8
在迭代 2 数组之前是:1 2 7 3 6 8
索引 2 和 5 之间的最小值为:索引 3 处的 3
交换索引 3 和 2
迭代 2 后数组为:1 2 3 7 6 8
在迭代 3 数组之前是:1 2 3 7 6 8
索引 3 和 5 之间的最小值为:索引 4 处为 6
交换索引 4 和 3
迭代 3 后数组为:1 2 3 6 7 8
迭代前 4 数组为:1 2 3 6 7 8
索引 4 和 5 之间的最小值为:索引 4 处为 7
本次迭代无需交换。
迭代 4 后数组为:1 2 3 6 7 8