2015-08-23 126 views
-1

我正在嘗試使用C++程序以升序和降序對數組進行排序。我只創建了使用桶排序的升序:桶排序降序?

void bucketSort (int data[], int n) 
{ 
int x = 65537; //range is [1,65536] 
int buckets[x]; //Create empty buckets 
for (int i = 0; i < x; i++) //Initialize all buckets to 0 
buckets[i] = 0; 

//Increment the # of times each element is present in the input 
//array. Insert them in the buckets 
for (int i = 0; i < n; i++) 
buckets[data[i]]++; 

//Sort using insertion sort and link 
for (int i = 0, j = 0; j < x; j++) 
for (int k = buckets[j]; k > 0; k--) 
    data[i++] = j; 
} 

但我不知道如何以降序排列。任何幫助都會很棒。

回答

0

你在這裏做的是counting sort而不是bucket sort

現在,按降序排列的元素進行排序,更改第三for循環如下:

for(int i = 0, j = x; j >= 0; j--)) 
+0

謝謝你提醒我,我糊塗了用水桶和計數排序。 –

0

std::reverse(data, data + n)末,

或降序迭代桶。 (j = x - 1 to 0