c - 按 C 中元素出现频率的降序对数组进行排序

标签 c arrays sorting frequency

题目是根据元素出现的频率对数组进行排序。例如,如果输入数组是

   { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 }

然后将数组修改为:

   { 3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5 }

我为此编写了代码并且它工作正常,但它占用了大量空间并且非常复杂。

我对这个解决方案和我为此申请的逻辑不满意。谁能帮助优化此代码或提供更好的逻辑?

我的代码是:

#define _CRT_SECURE_NO_WARNINGS // this line to work code in visual studio
#include <stdio.h>

int main() {
    /*
     * n = number of integer
     * i = loop variable
     * j = inner loop variable
     * c = number of distinct input
     * buf = temprary storage for input value
     * k = possibility of frequency of any no.
     */

    int n, i, j, c = 0, buf, k;
    int b; //act as flag
    int arr[100] = { 0 };
    int stack[200] = { 0 };
    int top = -1;
    printf("Enter the size of array(integer between 1-100):");
    scanf("%d", &n);
    n *= 2;

    printf("----------Enter the elements in the array----------\n\n");

    for (i = 0; i < n; i += 2) {
        b = 0;
        printf("Enter the element:");
        scanf("%d", &buf);
        for (j = 0; j <= i; j += 2) {
            if (arr[j] == buf) {
                arr[j + 1]++;
                b = 1;
            }       
        }
        if (b == 0) {
            c++;
            arr[c * 2 - 2] = buf;
            arr[c * 2 - 1]++;
        }
    }

    for (i = 0; i < c * 2; i++)
        printf("%d ", arr[i]);

    //input done in form of (element,times of occurence i.e. frequency),to print array, write this outside of comment: 
    //for (i = 0; i < c * 2; i++) printf("%d ", arr[i]);

    for (k = 1; k < n / 2; k++) {   //checking for possible frequencies
        for (j = c * 2 - 1; j > 0; j -= 2) {
            //locations(index) to check in array for frequency
            //left to right, so with same frequency no.,which occurred first will push in last.
            if (arr[j] == k)
                stack[++top] = j; //pushing(index of frequency) into stack in increasing order of frequency     
        }
    }

    //to print stack, write this outside of comment:
    //printf("\nstack\n");
    //for (i = top; i > -1; i--) printf("%d ",stack[i]);

    //printing of elements in there decreasing order of frequency(pop from stack)
    //we have to print element, number of times of its frequency

    printf("\n\n----------Output array in sorted order of there frequency----------\n");
    for (top; top > -1; top--) {        
        for (j = arr[stack[top]]; j > 0; j--)
            printf("%d ", arr[stack[top] - 1]);
    }
}

最佳答案

按值对数组进行排序; RLE 结果,将 equals 的每个跨度变成一对元素和跨度的长度(您可以使用辅助数组来支持第二个组件);按第二个分量降序排列对;这是你的结果。全部在 O(n log n) 时间和 O(n) 额外空间内。

关于c - 按 C 中元素出现频率的降序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129964/

相关文章:

c - 如何编译这个C程序?

c - 如何初始化指向结构的指针数组?

使用-std=gnu99 和内联函数时的编译错误

python - 从嵌套字典创建二维数组

java - 如何在 Java 中将 Set 排序为列表?

c++ - 在 C/C++ 中初始化和归零数组的区别?

C(动态)数组(固定大小)

c - C中的无符号字符数组串联

Javascript - 按一个属性分组,按另一个属性排序

php - 排序PHP数组升序