从未排序的数组中获取排序的订单索引 [英] Get sorted order indices from an unsorted array

查看:69
本文介绍了从未排序的数组中获取排序的订单索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个程序来从数字数组中返回排序后的索引:

I need a program to return the sorted order indices from an array of numbers:

a[4] = {10,7,2,3}; // input
b[4] = {4,3,1,2}; // expected output



a[4]中,最低元素是2(arrayindex = 2),数组索引2的输出值应附加到1,第二最低元素是3(array index = 3) ,数组索引3的输出值应附加到2.

有人可以帮忙这个程序吗?

问候
Steve



In a[4] lowest element is 2 (arrayindex = 2), output value of array index 2 should be append to 1, and 2nd lowest element is 3 (array index = 3), output value of array index 3 should be append to 2.

Can any one help with this program?

Regards
Steve

推荐答案

由于您的输出数组"看起来仅包含输入数组对应项的顺序(按递增顺序排列),因此您可以执行以下操作: br/>
Since your ''output array'' looks containing just the order of the corrensponding item of the input array (when increasingly ordered), you may do:
int i, j;
for (i = 0; i < 4; i++)
{
  b[i] = 0;
  for (j = 0; j < 4; j++)
  {
    if (a[i] >= a[j]) 
      b[i]++;
  }
}


:)


阅读了5次您的问题后,我想我知道您想要什么了.

我本想尝试阐明您要做的更好的事情,但是要解释这是一件相当棘手的事情; P

此代码产生与变量b相同的输出.
After reading your question 5 times I think I understand what u want.

I was going to try and clarify what you are trying to do better, but it is a rather tricky thing to explain ;P

This code produces the same output as your variable b.
#include <stdio.h>
#include <limits.h>
int main() {
    int pGapArray[] = { 10, 7, 2, 3 }; //Your a[], the input array
    int pNoGapArray[sizeof(pGapArray) / sizeof(pGapArray[0])];
    int nLowestIdx = 0; //This is equal to the index of the lowest number yet to be processed
    int nLowestVal = INT_MAX; //This is equal lowest number yet to be processed
    int nMinLowest = -1; //This is equal to the highest number we have processed
    int nValue = 1; //This is equal to the value we are writing to pNoGapArray
    for (int nIndex = 0; nIndex < sizeof(pGapArray) / sizeof(pGapArray[0]); ++nIndex) {
        nLowestVal = INT_MAX; //Reset the lowest value found
        for (int nSearch = 0; nSearch < sizeof(pGapArray) / sizeof(pGapArray[0]); ++nSearch) {
            if (pGapArray[nSearch] < nLowestVal && pGapArray[nSearch] > nMinLowest) {
                nLowestIdx = nSearch;
                nLowestVal = pGapArray[nSearch];
            }
        }
        nMinLowest = pGapArray[nLowestIdx];
        pNoGapArray[nLowestIdx] = nValue++;
    }
    printf("  pGapArray[] = { ");
    for (int nIndex = 0; nIndex < sizeof(pGapArray) / sizeof(pGapArray[0]); ++nIndex) {
        printf("%d, ", pGapArray[nIndex]);
    }
    printf("};\n");
    printf("pNoGapArray[] = { ");
    for (int nIndex = 0; nIndex < sizeof(pNoGapArray) / sizeof(pNoGapArray[0]); ++nIndex) {
        printf("%d, ", pNoGapArray[nIndex]);
    }
    printf("};\n");
    return 0;
}


这篇关于从未排序的数组中获取排序的订单索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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