#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; }