考慮下面的代碼:
#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);
}
輸出:
Before iteration 0 array is: 2 6 7 3 1 8
Minimum between indices 0 and 5 is: 1 at index 4
Exchanging indices 4 and 0
After iteration 0 array is: 1 6 7 3 2 8
Before iteration 1 array is: 1 6 7 3 2 8
Minimum between indices 1 and 5 is: 2 at index 4
Exchanging indices 4 and 1
After iteration 1 array is: 1 2 7 3 6 8
Before iteration 2 array is: 1 2 7 3 6 8
Minimum between indices 2 and 5 is: 3 at index 3
Exchanging indices 3 and 2
After iteration 2 array is: 1 2 3 7 6 8
Before iteration 3 array is: 1 2 3 7 6 8
Minimum between indices 3 and 5 is: 6 at index 4
Exchanging indices 4 and 3
After iteration 3 array is: 1 2 3 6 7 8
Before iteration 4 array is: 1 2 3 6 7 8
Minimum between indices 4 and 5 is: 7 at index 4
No exchange necessary this iteration.
After iteration 4 array is: 1 2 3 6 7 8
'find_min'應該是'的std :: min_element'。 – chris
@chris如果OP實際取代它,只是名稱:D – P0W
最小元素究竟能夠「找不到」?數組中的**元素不會是最小的元素嗎?出於某種深不可測的原因,find_min選擇當最小元素位於索引0時返回-1。 –