简单选择排序
#include<stdio.h> #include<assert.h> void display(int * a, int n) { assert(a); for(int i = 0; i < n; i++) { printf("%d,",a[i]); } printf("\n"); } void swap(int * a, int * b) { assert(a); assert(b); int temp; temp = *a; *a = *b; *b = temp; } void select_sort(int * a, int n) { assert(a); int i, j,min; for( i = 0; i < n-1 ; i++) //i 0 ~ n-2 { min = a[i]; //每次选择一个作为最小值 for( j = i; j < n; j++) // j i ~ n-1 { if(a[j] < min) { swap(&(a[j]), &(a[i])); } } } } int main() { int a[10] ={2, 1, 3, 4, 5, 7,2,3, 6, 1}; int num = sizeof(a)/sizeof(int); printf("before_sort:"); display(a, num); select_sort(a,num); printf("after_sort:"); display(a, num); return 0; }
#include <stdio.h> #include <time.h> //交换两个数据 void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } //显示交换后的数组 void display_array( int a[], int n ) { int i; for( i = 0; i < n; i++ ) printf( "%d ", a[i] ); } //选择排序 void select_sort( int a[], int n ) { int i ,j; for(i = 0; i<n-1 ; i++ ) { int min = a[i]; //每次都设定最小的数,i 0 ~ 8 for(j =i+1; j <n; j++) // 将a[i]~ a[9]的数于当前最小的数进行比较,如果小于当前最小数就交换 { if(a[j] < min) { swap(&(a[j]), &(a[i])); } } } } int main() { clock_t start, finish; start = clock(); int n = 10; int a[] = { 2, 1, 3, 4, 5, 7, 6, 8 ,2,4}; printf( "Before sorting: " ); display_array( a, n ); select_sort( a, n ); printf( "After sorting: " ); display_array( a, n ); finish = clock(); printf("\n本次计算一共耗时: %f秒\n\n", (double)(finish-start)/CLOCKS_PER_SEC); return 0; }
补充:软件开发 , C++ ,