桶排序是一種效率很高的排序算法,它的時間復雜度為O(N+M),(N個元素,范圍為0--M),但桶排序有一定的限制,必須為非負整數,而且元素不宜過大。
算法思想:
設待排序序列的元素取值范圍為0到m,則我們新建一個大小為m+1的臨時數組並把初始值都設為0,遍歷待排序序列,把待排序序列中元素的值作為臨時數組的下標,找出臨時數組中對應該下標的元素使之+1;然后遍歷臨時數組,把臨時數組中元素大於0的下標作為值按次序依次填入待排序數組,元素的值作為重復填入該下標的次數,遍歷完成則排序結束序列有序。
1 void BucketSort(int intArray[], int Count_intArray, int max) 2 { 3 //待排序序列intArray的元素都是非負整數 4 //設待排序序列intArray的元素有Count_intArray個 5 //其取值范圍為0到max,則我們新建一個大小為max+1的臨時數組並把初始值都設為0 6 //此處是開辟max+1而不是max,因為比如給909,...0排序,是有1000個數,需要開辟999+1長度的數組 7 int *TmpArray = (int*)malloc(sizeof(int)*(max+1));//開辟一個新數組,這個數組即為桶; 8 for (int *p = TmpArray; p < TmpArray + max+1 ; p++) *p = 0;//初始化桶,是桶中的每個元素為0; 9 for (int *p = intArray; p < intArray + Count_intArray; p++) TmpArray[*p] += 1;///將TmpArray下標中等於intArray[i]的元素+1 10 int InsertIndex = 0;//指向intArray的指標 11 for (int j=0; j < max + 1; j++) 12 { 13 for (int k = 1; k <= TmpArray[j]; k++)//需要插入的元素的個數必須>1 14 intArray[InsertIndex++] = j; 15 } 16 free(TmpArray); 17 }
該例程輸入待排序整形矩陣intArray,元素個數Count_intArray,以及元素最大值max(該max其實只要大於元素中最大的值就行)。
測試函數
1 #include<stdio.h> 2 #include<malloc.h> 3 int main() 4 { 5 void BucketSort(int intArray[], int Count_intArray,int max); 6 int intArray[10] = { 999,55,10,1,0,1,87,45,55,4 }; 7 int Count_intArray = 10; 8 int max = 999; 9 BucketSort(intArray, Count_intArray, max); 10 for (int i = 0; i < 10; i++) 11 printf("%d ", intArray[i]); 12 printf("\n"); 13 }
結果: