C++: selection sort

来源:互联网 发布:淘宝网如何开店铺步骤 编辑:程序博客网 时间:2024/06/05 06:03

关于selection sort , 无需多说。

关于selection sort算法的分析:

(1)比较的次数总是O(n^2), 赋值的次数为O(n),

(2)一般而言, 该排序算法仅对小的List 效果比较好。因为算法的复杂度很大, 也就是随着输入规模的增大时间复杂度增长很快。, 达到O(n^2), 然而, 当如果数据的移动的代价很大的时候, 但是进行数据间的比较的代价较小的时候, 这个排序算法可能是一个better choice over other sorting algorithms.

//selection sort for array based list#include <iostream>#include <ctime>#include <cstdlib>#include <iomanip>using namespace std;// find the minimum loactiontemplate <class elemType>void print(elemType list[], int length);template <class elemType>int minLocation(elemType[], int, int);// do swaptemplate <class elemType>void swap(elemType[], int, int);//selection sort 总程序template <class elemType>void selectionSort(elemType[], int);int main() {   int intList[100];   int num;   for (int i = 0; i < 100; i++){      num = (rand() + time(0)) %1000;      intList[i] = num;   }   cout << "intList before sorting: " << endl;   print(intList, 100);   cout << endl << endl;   selectionSort(intList, 100);   cout << "intList after selection sort: " << endl;   print(intList, 100);   cout << endl;   system("Pause");   return 0;}template <class elemType>void print(elemType list[], int length) {   int count = 0;   for(int i = 0; i < length; i++) {      cout << setw(5) << list[i];      count++;      if(count % 10 == 0)         cout << endl;   }}template <class elemType>int minLocation(elemType list[], int first, int last) {   int minIndex = first;   for(int loc = first + 1; loc <= last; loc++) {      if (list[loc] < list[minIndex])         minIndex = loc;   }   return minIndex;}template <class elemType>void swap(elemType list[], int first, int second) {   elemType temp;   temp = list[first];   list[first] = list[second];   list[second] = temp;}template <class elemType>void selectionSort(elemType list[], int length) {   int minIndex;   for (int loc = 0; loc < length - 1; loc++) {      minIndex = minLocation(list, loc, length - 1);      swap(list, loc, minIndex);   }}


运行结果如下:

 

0 0
原创粉丝点击