如何在C中查找数组中的前6个元素 [英] How to find top 6 elements in an array in C

查看:195
本文介绍了如何在C中查找数组中的前6个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中找到具有排序顺序的前6个元素.

I am trying to find top 6 elements from an array with their ordering number.

    int x=0;

for (int k = 0; k < 6; k++) //
{
    for (i = 1; i <= 90; i++)
    {
        if (sorted[k] < holder[i] && i >= x)
        {
            sorted[k] = holder[i];
            x = i; //
        }
    }
}

但这不起作用.我希望它给我类似43-> 7 15-> 3等的输出.

But this does not work. I want it to give me output like 43->7 15 ->3 etc..

推荐答案

有一段时间没有写C了,但这是一个简单的解决方案,可以修改数组并使用选择排序选择k最高数字在数组中并将它们移到最前面.它会保留一个与数字原始位置相对应的索引数组,并对它应用相同的交换.

Haven't written C in a while, but here is a simple solution that modifies the array in place and uses selection sort to select the k highest numbers in the array and moves them to the front. It keeps an array of indices that correspond to where the number originally was and applies the same swaps to it.

#include <stdio.h>
#define ELEMENTS 10

void main(void)
{
    // example input for execution
    int numbers[10] = {9,4,5,1,8,2,3,6,0,7};
    // tracks ordering of indices
    int indexes[10] = {0,1,2,3,4,5,6,7,8,9};
    int k = 6;

    int i, j;
    int max, temp;

    // Partial selection sort, move k max elements to front
    for (i = 0; i < k; i++)
    {
        max = i;
        // Find next max index
        for (j = i+1; j < ELEMENTS; j++)
        {
            if (numbers[j] > numbers[max])  {
                max = j;
            }
        }
        // Swap numbers in input array
        temp = numbers[i];
        numbers[i] = numbers[max];
        numbers[max] = temp;
        // Swap indexes in tracking array
        temp = indexes[i];
        indexes[i] = indexes[max];
        indexes[max] = temp;
    }

    for (i = 0; i < k; i++) {
        printf("%d -> %d\n", indexes[i], numbers[i]);
    }
}

输出:

0 -> 9
4 -> 8
9 -> 7
7 -> 6
2 -> 5
1 -> 4

这篇关于如何在C中查找数组中的前6个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆