选择排序
来源:互联网 发布:单片机pwm模块长啥样 编辑:程序博客网 时间:2024/05/23 19:18
选择排序
思路:eg:降序,选择一个大的数下标,最后从第一个开始交换大的数的下标,不断地缩小范围
时间复杂度:O(N2);
注:俩种选择排序的时间复杂度是最稳定的,不会因为任何原因而有所变化;
如下图:
初学C语言的版本
<span style="font-size:18px;">#include<stdio.h>void sort(int a[], int len){int i, j, k;for (i = 0; i<len - 1; i++){k = i;for (j = i + 1; j<len; j++){if (a[k]<a[j]){k = j;}}if (k != i){int tmp = a[i];a[i] = a[k];a[k] = tmp;}}for (i = 0; i<len; i++){printf("%d ", a[i]);}printf("\n");}int main(){int a[] = { 2, 9, 5, 8, 3, 6, 1, 7, 0, 4 };sort(a, sizeof(a) / sizeof(a[0]));return 0;}</span>初学C++版本及其优化版本
注:初学C++版本思路与C语言中的思路相同,但是C++优化版本的思路:同时从俩端缩小范围,不仅交换大的数的下标位置,还要交换小的数的小标位置。
代码如下:
<span style="font-size:18px;">#include<iostream>using namespace std;//选择排序void SelectSort(int* arr,int len){if (arr == NULL || len <= 0)return;for (int end = len - 1; end > 0; --end){int maxIndex = 0;for (int i = 1; i < end+1; ++i){if (arr[maxIndex] < arr[i]){maxIndex = i;}}if (maxIndex != end){swap(arr[maxIndex], arr[end]);}}}//选择排序的优化void SelectSort_B(int* arr,int len){if (arr == NULL || len <= 0)return;for (int end = len - 1; end > 0; --end){int minIndex = len - end - 1;int maxIndex = end;for (int i = len - end - 1; i < end + 1; ++i){if (arr[minIndex] > arr[i]){minIndex = i;}if (arr[maxIndex] < arr[i]){maxIndex = i;}}swap(arr[maxIndex], arr[end]);//当大的在小的位置或者小的在大的位置时if (minIndex == end)minIndex = maxIndex;swap(arr[minIndex], arr[len - end - 1]);}}//测试用例void TestSelectSort(){int array[10] = { 2, 9, 5, 8, 3, 6, 1, 7, 0, 4 };SelectSort(array, 10);Print(array, 10);}void TestSelectSort_B(){int array[10] = { 2, 9, 5, 8, 3, 6, 1, 7, 4, 0 };SelectSort_B(array, 10);Print(array, 10);}</span>
测试结果如下图所示:
1 0
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序:
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- elasticsearch JAVA客户端操作---索引的CURD
- 3.4
- 【Android开发】图形图像处理技术-常用绘图类之Paint类
- 将Eclipse中的项目迁移到Android Studio 中
- 回溯算法之n皇后问题
- 选择排序
- PCB过孔对信号传输的影响
- 了解lua setmetatable和__index的小例子
- 3.5
- UIImagePickerController
- Linux: 操作系统
- error C4996: 'setmode': The POSIX name for this item is deprecated解决方案
- 线程(创建线程)
- 关于社交型产品-抱抱 产品分析(二)