选择排序

来源:互联网 发布:淘宝店铺月度运营计划 编辑:程序博客网 时间: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
原创粉丝点击