1. 程式人生 > >(排序演算法)linux c語言實現快速排序(氣泡排序的改進版)

(排序演算法)linux c語言實現快速排序(氣泡排序的改進版)

 快速排序演算法是對氣泡排序演算法的一種改進,氣泡排序是對單個元素的升降,快速排序是對所有元素的升降,不過這個升降是取了某一個標準的前提下,在本文程式碼中,就以a[i],其實就是以最左邊的元素為參考,比較交換之後,將這個參考元素放到分界的地方,即i的位置。

程式碼如下,裡面有比較詳細的註釋。

/***************************************************
##filename      : quicksort.c
##author        : GYZ                               
##e-mail        : 
[email protected]
##create time : 2018-10-31 09:54:39 ##last modified : 2018-11-05 14:15:50 ##description : NA ***************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> void quickSort(int a[],int low,int high) { int i = low; int j = high; int temp = a[i]; /*判斷遞迴是否結束*/ if(low < high) { /*迴圈相向而行,到兩個下標值相等時,迴圈停止*/ while(i < j) { /*這個while將high -> j 中第一個小於temp的值給a[i]*/ while(a[j]>=temp && (i < j)) { --j; } a[i] = a[j]; /*這個while將low -> i 中第一個大於temp的值給a[j]*/ while(a[i]<=temp && (i < j)) { ++i; } a[j] = a[i]; /*這兩個while的結果就是以temp為比較值,大的分到右邊,小的分到左邊*/ } a[i] = temp; /*上面的while之後,i(或者j)的位置,就是temp的位置,因為剛剛i左邊是小於temp的值,右邊是大於temp的值,所以i對應的就是temp*/ quickSort(a,low,i-1); /*進入左半部分進行比較,遞迴*/ quickSort(a,j+1,high); /*進入右半部分進行比較,遞迴*/ } else { return ; } } /*bubble sort*/ /*void bubbleInsert(int a[],int n) { int temp = 0; int i = 0,j = 0; for(i = 0; i < n; ++i) { for(j = i+1; j < n; ++j) { if(a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } }*/ void printArr(int a[],int n) { int i; for(i = 0; i < n; i++) { printf("%d,",a[i]); } printf("\n"); } int main(int argc,char *argv[]) { int length = 0; int begin,end; int a[] = {26,20,10,14,15,21,22,23,24,25,28,29,30,3,5,6,1,9,4,8,2,7,11,13,12,27,18,19,16,17}; length = sizeof(a) / sizeof(a[0]); begin = clock(); quickSort(a,0,length); // bubbleInsert(a,length); end = clock(); printf("%d\n",end-begin); printArr(a,length); return 0; }