桶排序降序

Bucket sort descending order?

本文关键字:降序 桶排序      更新时间:2023-10-16

我正在尝试使用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;
}

但是我不知道如何按降序排列。

你在这里做的是计数排序,而不是桶排序。

现在,要按降序对元素进行排序,更改第三个for循环如下:

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

std::reverse(data, data + n)结尾,

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