如何按值对数组进行排名(排序)?*有一点扭曲* [英] How does one rank an array (sort) by value? *With a twist*

查看:36
本文介绍了如何按值对数组进行排名(排序)?*有一点扭曲*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 C/C++ 按升序对数组进行排序.结果是一个包含元素索引的数组.每个索引对应于已排序数组中的元素位置.

I would like to sort an array in ascending order using C/C++. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.

示例

Input:  1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4

我正在使用外壳排序程序.重复值索引是根据原始数组中重复值在前的任意选择.

I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.

尽管我尽了最大的努力,但我还没有能够为指针数组实现排序算法.当前示例无法编译.

Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.

有人能告诉我有什么问题吗?

Could someone please tell me what's wrong?

非常感谢您的帮助!

void SortArray(int ** pArray, int ArrayLength) 
{
    int i, j, flag = 1;    // set flag to 1 to begin initial pass
    int * temp;    // holding variable orig with no *
    
    for (i = 1; (i <= ArrayLength) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (ArrayLength - 1); j++)
        {
            if (*pArray[j + 1] > *pArray[j])    // ascending order simply changes to <
            { 
                &temp = &pArray[j];    // swap elements
                &pArray[j] = &pArray[j + 1];    //the problem lies somewhere in here
                &pArray[j + 1] = &temp;
                flag = 1;    // indicates that a swap occurred.
            }
        }
    }
};

推荐答案

由于您使用的是 C++,我会这样做.SortIntPointers 函数可以是任何排序算法,重要的是它根据指针指向的 int 对指针数组进行排序.完成后,您可以遍历指针数组并分配它们的排序索引,该索引将在原始数组中的原始位置结束.

Since you're using C++, I would do it something like this. The SortIntPointers function can be any sort algorithm, the important part is that it sorts the array of pointers based on the int that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.

int* intArray; // set somewhere else
int arrayLen;  // set somewhere else  

int** pintArray = new int*[arrayLen];
for(int i = 0; i < arrayLen; ++i)
{
    pintArray[i] = &intArray[i];
}

// This function sorts the pointers according to the values they
// point to. In effect, it sorts intArray without losing the positional
// information.
SortIntPointers(pintArray, arrayLen);

// Dereference the pointers and assign their sorted position.
for(int i = 0; i < arrayLen; ++i)
{
    *pintArray[i] = i;
}

希望这已经足够清楚了.

Hopefully that's clear enough.

这篇关于如何按值对数组进行排名(排序)?*有一点扭曲*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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