I'm writing a selection sort that, given an array of unordered elements, will fill a new array with the indexes of the sorted elements. For example,
[3, 2, 1]
would return
[2, 1, 0] // original indexes of sorted array [1, 2, 3]
Unfortunately, it fills the array incorrectly, repeating the same index over an over.
This is my code:
void sort(float data[], int indx[], int len) {
int min;
float temp;
float tempData[len];
for (int x = 0; x < len; ++x){
tempData[x] = data[x];
}
for (int i = 0; i < len; ++i) {
min = i;
for (int j = i + 1; j < len; ++j) {
if (tempData[j] < tempData[min]) {
min = j;
}
}
temp = tempData[i];
tempData[i] = tempData[min];
tempData[min] = temp;
indx[i] = min;
}
}
And given this array:
[8.5, 10.0, 9.25, 12.5, 12.75, 12.5, 16.0, 14.75, 17.0, 18.0, 21.0, 13.0, 7.25];
it returns:
[12, 12, 2, 12, 5, 12, 12, 11, 11, 12, 11, 12, 12]
I can't seem to figure out where the logic error is occurring. Could someone help me find it?