C++: selection sort

关于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 loaction

template <class elemType>
void print(elemType list[], int length);

template <class elemType>
int minLocation(elemType[], int, int);

// do swap

template <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);
   }
}



运行结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值