选择排序
来源:互联网 发布:淘宝店铺月度运营计划 编辑:程序博客网 时间:2024/06/18 12:23
继续说排序。
这次说一个选择排序,也是非常容易想到的排序方法:每次选出最小的一个,放在最前面,然后在剩下的里面再选一个最小的,放在第二位,如此下去直到剩最后一个为止。用代码实现如下:
#include <stdio.h>#include <stdlib.h> #define SIZE_ARRAY_1 5#define SIZE_ARRAY_2 6#define SIZE_ARRAY_3 20void selection_sort(int a[], int n);void showArray(int a[], int n);void main(){int array1[SIZE_ARRAY_1]={1,4,2,-9,0};int array2[SIZE_ARRAY_2]={10,5,2,1,9,2};int array3[SIZE_ARRAY_3];for(int i=0; i<SIZE_ARRAY_3; i++){array3[i] = (int)((40.0*rand())/(RAND_MAX+1.0)-20);}printf("Before sort, ");showArray(array1, SIZE_ARRAY_1);selection_sort(array1, SIZE_ARRAY_1);printf("After sort, ");showArray(array1, SIZE_ARRAY_1);printf("Before sort, ");showArray(array2, SIZE_ARRAY_2);selection_sort(array2, SIZE_ARRAY_2);printf("After sort, ");showArray(array2, SIZE_ARRAY_2);printf("Before sort, ");showArray(array3, SIZE_ARRAY_3);selection_sort(array3, SIZE_ARRAY_3);printf("After sort, ");showArray(array3, SIZE_ARRAY_3);}void showArray(int a[], int n){if(n>0)printf("This array has %d items: ", n);elseprintf("Error: array size should bigger than zero.\n");for(int i=0; i<n; i++){printf("%d ", a[i]);}printf("\n");}/* selection_sort * Principle: Divide array into two parts: sorted part and unsorted * part, select the smallest/largest element and swap with the most * left element of unsorted part. */void selection_sort(int a[], int n){if(n<=0)return;for(int j=0;j<n-1;j++) {// find the smallest one in a[j..n-1]int min=a[j];int index=j;for(int i=j;i<n;i++) {if(a[i]<min) {min=a[i];index=i;}}// swapa[index]=a[j];a[j]=min;}}
0 0
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序:
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- ubuntu 中使用vi 编辑器时无法正常使用快捷键相关问题
- Android通过USB与PC通信
- 交换两个值,而不用临时变量
- Android的线程使用来更新UI----Thread、Handler、Looper、TimerTask等
- 1176C语言实验——删除指定字符
- 选择排序
- 第十六天【java虐我千百遍,我待java如初恋】
- Heap dump
- HSQLDB
- Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
- ibatis学习
- java webservice cfx
- ubuntu 启动修复
- Oracle收集索引统计信息