c - 数组百分比算法实现

标签 c arrays algorithm sorting max

所以我几天前才开始用 C 编程,我有一个程序,它接受一个充满整数的未排序文件,使用快速排序对其进行排序 第一种算法

对我在这方面做错了什么有什么建议吗?

最佳答案

根据您的描述,听起来您快到了。您正在尝试获取一个集合的第一个元素,该元素的值等于(或刚好大于)该集合所有其他成员的 90%。你已经完成了排序。其余的应该简单地遵循这些步骤(如果我理解你的问题):

1) 将集合排序到 into 数组中(我想你已经这样做了)
2) 统计集合中的个数,存入float n;//集合中的元素个数
3) 通过排序数组索引到第 0.9*n 个元素,(选择超过该点的第一个元素,而不是前一个元素的副本)
4)显示结果

这是我所描述内容的实现(某种程度上,我没有存储 n):(忽略随机数生成器, 等, 这只是一种快速获取数组的方法)

#include <ansi_c.h>
#include <windows.h>
int randomGenerator(int min, int max);
int NotUsedRecently (int number);
int cmpfunc (const void * a, const void * b);

int main(void)
{
    int array[1000];
    int i;

    for(i=0;i<1000;i++)
    {
        array[i]=randomGenerator(1, 1000);
        Sleep(1);
    }

    //sort array
    qsort(array, 1000, sizeof(int), cmpfunc);

    //pick the first non repeat 90th percent and print
    for(i=900;i<999;i++)
    {
        if(array[i+1] != array[i])
        {
            printf("this is the first number meeting criteria: %d", array[i+1]);
            break;
        }
    }
    getchar();  

    return 0;
}






int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}


int randomGenerator(int min, int max)
{
    int random=0, trying=0;

    trying = 1;         
    srand(clock());
    while(trying)
    {

        random = (rand()/32767.0)*(max+1);
        (random >= min) ? (trying = 0) : (trying = 1);
    }

    return random;
}

这是我的第一个随机生成的数组(以第 90 个百分位数为中心)的输出,与算法选择的内容进行比较:左边的列是元素编号,右边的列是随机生成的整数的排序列表。 (注意它会跳过重复以确保最小值过去 90%)

enter image description here enter image description here

总结:正如我所说,我认为您已经,差不多了。请注意我的代码的这一部分与您的代码有多么相似:

enter image description here

你已经有了一些东西,非常相似。只需修改它以开始查看数组的 90% 索引(无论那是什么),然后只选择不等于前一个的第一个值。

关于c - 数组百分比算法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19982843/

相关文章:

python - 如何在python中加速多个内积

algorithm - 大 o 复杂度尺度函数 (n+1)^5/4n^2

c++ - 为什么我们将 greater<string>() 传递给排序算法?

c - 我正在用 C 创建一个数组,它计算数组的乘积

c - 关于在 C 中使用递归

php - 展平多维数组连接键

javascript - 数组类型被拾取为数组值

c - 如何为每个玩家生成不同的随机数?

c - http 套接字请求返回尾随字符

python - 如何将 numpy ND 数组转换为 CFFI C++ 数组并再次转换回来?