铲斗降序排序?

时间:2015-08-23 14:12:54

标签: c++ sorting

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

但我不知道如何按降序排列。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

std::reverse(data, data + n)最后,

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

答案 1 :(得分:0)

你在这里做的是counting sort,而不是bucket sort

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

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