I am trying to build a function in C/C++ to sort an array and replace each value with its ‘score’ or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can’t get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:
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]; pArray[j+1] = &temp; flag = 1; // indicates that a swap occurred. } } } }
You’re close. You’re referencing the address of the array items when you swap, which isn’t necessary. The items in the array are pointers, and that’s what needs to be swapped.
See below:
Also, check out this lovely blog post on Bubble Sorting in case you’re interested (sorry, shameless plug :)). Hope that helps you with your homework 😉
Edit: Note the subtle ‘optimisation’ where you count back from the array length and only increment up until ‘i’ in the inner loop. This saves you from needlessly reparsing items that have already been sorted.