简单选择排序

来源:互联网 发布:php获取服务器ip地址 编辑:程序博客网 时间:2024/06/05 20:13

1,思路:

选择排序是固定位置找元素,(插入排序是固定元素找位置)。

比如要找最小的元素,即0号位置元素,就要先找出数组的最小元素,和0号元素互换;接着找次小的元素就是从剩下的length-1个元素里找最小的元素然后和1号位置元素互换,直到所有位置元素都确定为止。

2,简单代码

#include "stdafx.h"#include <iostream>#include <ctime>using namespace std;void selectsort(int *a, int length){int index;int val;int temp;int i,j;for (i = 0; i < length; i++){index = i;val = a[i];for (j = i + 1; j < length; j++){if (a[j] < val){val = a[j];index = j;}}if (i == j){continue;}temp = a[index];a[index] = a[i];a[i] = temp;}}int _tmain(int argc, _TCHAR* argv[]){int length;cout << "输入数组规模!" << endl;cin >> length;int *a = new int[length];cout << "随机数组为:" << endl;srand((int)time(0));for (int i = 0; i < length; i++){a[i] = rand()%11;cout << a[i] << ' ';}cout << endl;selectsort(a, length);cout << "选择排序后为:" << endl;for (int j = 0; j < length; j++){cout << a[j] << ' ';}cout << endl;system("pause");return 0;}
3,时间复杂度为O(n2)。

 此方法移动元素的次数比较少,但是不管序列中元素初始排列状态如何,第 i 趟排序都需要进行 n - i 次元素之间的比较,因此总的比较次数为

1 + 2 + 3 + 4 +5 + . . . + n - 1 = n(n-1)/2, 时间复杂度是 O(n^2).

空间复杂度为O(1)。

0 0
原创粉丝点击