1、算法说明
假设:有n个元素的数组array[n-1],未进行排序,现要求从小到大进行排序。
第一轮:从下标0(array[0])开始,将此元素(数字)与下标1(array[1])进行比较,如果不满足要求则交换,直至与最后一个元素(array[n-1])比较并排序为止。
第二轮:从下标1(array[1])开始,将此元素(数字)与下标2(array[2])进行比较,如果不满足要求则交换,直至与最后一个元素(array[n-1])比较并排序为止。
...
最后一轮(第n-1轮):比较array[n-2]与array[n-1]两个元素并排序。
2、代码
#include <iostream>
using namespace std;
#define debug 1
void sort_select(int *array, int len);
void swap(int *pa, int *pb);
void output(int *array, int len);
int main(int argc, char *argv[])
{
int num = 0;
cout << "Please input an integer." << endl;
cin >> num;
if(num <= 0) return 0;
int array[num];
cout << "Please input " << num << " integers." << endl;
for(int i = 0; i < num; i++) cin >> array[i];
if(debug) {
cout << "Before sorting, the numbers are as following:" << endl;
output(array, num);
}
sort_select(array, num);
if(debug) cout << "After sorting, the numbers are as following:" << endl;
output(array, num);
return 0;
}
/***************************************
Function: sort_select
Arguments:
array: pointer to an array of integers.
len: length of the array.
Algorithm:
Compare the first integer with all others and swap if necessary each time.
Put the minimum number to the first after first round.
***************************************/
void sort_select(int *array, int len)
{
if(!array || len <= 0) return;
for(int i = 0; i < len - 1; i++) {
for(int j = i + 1; j < len; j++) {
if(debug) {
cout << i << ", " << j << ": ";
output(array, len);
}
if(array[i] > array[j]) {
swap(&array[i], &array[j]);
if(debug) {
cout << i << ", " << j << ": ";
output(array, len);
}
}
}
}
}
void swap(int *pa, int *pb)
{
if(!pa || !pb) return;
int t = *pa;
*pa = *pb;
*pb = t;
}
void output(int *array, int len)
{
if(!array || len <= 0) return;
for(int i = 0; i < len; i++) cout << array[i] << " ";
cout << endl;
}
3、调试说明
需要查看具体排序过程:
不需要查看具体排序过程:
4、运行结果
输入:
输出:
Please input an integer.
Please input 5 integers.
Before sorting, the numbers are as following:
5 4 3 2 1
0, 1: 5 4 3 2 1
0, 1: 4 5 3 2 1
0, 2: 4 5 3 2 1
0, 2: 3 5 4 2 1
0, 3: 3 5 4 2 1
0, 3: 2 5 4 3 1
0, 4: 2 5 4 3 1
0, 4: 1 5 4 3 2
1, 2: 1 5 4 3 2
1, 2: 1 4 5 3 2
1, 3: 1 4 5 3 2
1, 3: 1 3 5 4 2
1, 4: 1 3 5 4 2
1, 4: 1 2 5 4 3
2, 3: 1 2 5 4 3
2, 3: 1 2 4 5 3
2, 4: 1 2 4 5 3
2, 4: 1 2 3 5 4
3, 4: 1 2 3 5 4
3, 4: 1 2 3 4 5
After sorting, the numbers are as following:
1 2 3 4 5