如何按值对数组(排序)进行排名?*扭曲*

Ed.*_*Ed. 5 c c++ arrays sorting

我想用升序对数组进行排序C/C++.结果是包含元素索引的数组.每个索引都与排序数组中的元素位置相对应.

Input:  1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
Run Code Online (Sandbox Code Playgroud)

编辑:我正在使用shell排序程序.基于哪个重复值首先在原始数组中任意选择重复值索引.

更新:

尽管我付出了最大的努力,但我还是无法为指针数组实现排序算法.当前示例将无法编译.

有人可以告诉我有什么问题吗?

我非常感谢一些帮助!

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.
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

Zoo*_*oba 7

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

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;
}
Run Code Online (Sandbox Code Playgroud)

希望这很清楚.