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.
Example
Input: 1, 3, 4, 9, 6 Output: 1, 2, 3, 5, 4
Edit: I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.
Update:
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?
I’d very much appreciate some help!
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. } } } };
Since you’re using C++, I would do it something like this. The
SortIntPointersfunction can be any sort algorithm, the important part is that it sorts the array of pointers based on theintthat 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.Hopefully that’s clear enough.