我想通过增加频率顺序对数组进行排序。例如,如果我有一个数组
int arr[] = { 3, 3, 10, 2, 5, 10, 10, 2, 2, 2 };
或其他数组中将包含以下序列:
int arr[] = {5, 3, 3, 10, 10, 10, 2, 2, 2, 2};
但是,我不能使用散列或地图 - 我只能使用数组。我想到的是使用快速排序算法对数组进行排序,扫描排序的数组并在2d数组中执行计数,以便对于每个元素,有一个与之关联的计数,然后按计数排序。如果两个计数相同,那么我只打印出具有较低值的计数。我在执行最后两个步骤时遇到了麻烦。我不确定如何将计数“映射”到2d数组中的索引,也不确定如何按计数对2d数组进行排序。任何人都可以帮我吗?谢谢!
答案 0 :(得分:4)
扫描您的阵列(先排序优化,但不需要),然后生成下面结构的数组。现在对这些结构的数组进行排序,然后重新生成原始数组。
struct ElemCount {
int Elem;
int count;
bool operator<(const ElemCount& other) {
if (count!=other.count)
return count<other.count;
return Elem<other.Elem;
}
};
答案 1 :(得分:2)
这就是我在没有STL的情况下编码它(需要额外的O(n)内存):
// Represents a bunch of equal numbers in an array
struct Bunch
{
int x; // value of numbers
int n; // count of numbers
};
int cmp_int(const void *x, const void *y)
{
return *static_cast<const int*>(x) - *static_cast<const int*>(y);
}
int cmp_bunch(const void *x, const void *y)
{
const Bunch* bx = static_cast<const Bunch*>(x);
const Bunch* by = static_cast<const Bunch*>(y);
return (bx->n != by->n) ? bx->n - by->n : bx->x - by->x;
}
void sort_by_freq(int arr[], int arr_size)
{
// Buffer array to store counted bunches of numbers
Bunch* buf = new Bunch [arr_size];
int buf_size = 0;
// Sort input array
qsort(arr, arr_size, sizeof(int), cmp_int);
// Compute bunches
Bunch bunch;
bunch.x = arr[0];
bunch.n = 1;
for (int i = 1; i < arr_size; ++i)
{
if (arr[i] > bunch.x)
{
buf[buf_size++] = bunch;
bunch.x = arr[i];
bunch.n = 1;
}
else
{
++bunch.n;
}
}
buf[buf_size++] = bunch; // Don't forget the last one!
// Sort bunches
qsort(buf, buf_size, sizeof(Bunch), cmp_bunch);
// Populate bunches to the input array
int i = 0;
for (int k = 0; k < buf_size; ++k)
for (int j = 0; j < buf[k].n; ++j) arr[i++] = buf[k].x;
// Don't forget to deallocate buffer, since we cannot rely on std::vector...
delete [] buf;
}