选择排序是找到最小的之后在进行交换,相较于冒泡排序可以减少交换的次数。其代码实现如下:
Input number (q to quite): 9 6 4 1 3 8 4 6 9 7 2 3 6 q
Your input List is: 9 6 4 1 3 8 4 6 9 7 2 3 6
After bubble sort: 1 2 3 3 4 4 6 6 6 7 8 9 9
#include<iostream>
using namespace std;
#define MAXSIZE 100
struct List
{
int data[MAXSIZE];
int size;
};
void swap(List &L, int i, int j)
{
int temp = L.data[i];
L.data[i] = L.data[j];
L.data[j] = temp;
}
void show(const List &L)
{
for (int i = 0; i < L.size; i++)
cout << L.data[i] << " ";
cout << endl;
}
void SelectSort(List &L)
{
for (int i = 0; i < L.size - 1; i++) {
int idx = i;
for (int j = i+1; j < L.size; j++) {
idx = L.data[idx] < L.data[j] ? idx : j;
}
swap(L, i, idx);
}
}
void main()
{
List test;
cout << "Input number (q to quite): ";
int temp;
test.size = 0;
while (test.size <= MAXSIZE&&cin >> temp) {
test.data[test.size] = temp;
test.size += 1;
//cout << "Input number (q to quite): ";
}
cin.clear();
cin.ignore(100, '\n');
cout << "Your input List is: ";
show(test);
cout << "After bubble sort: ";
SelectSort(test);
show(test);
}
选择排序的时间复杂度为: O ( n 2 ) \ O(n^2) O(n2)