I have a project to create a scheduling program and one part of it requires sorting. I know how to do this with a regular bubble sort but the project asks me to do it this way...
sort() — a function to sort a floats array data[], creating an array of sorted indices. The sort() function does not sort the data, but fills the the array indx[] so that data[indx[0]], data[indx[1]], ..., data[indx[NUM_EVENTS - 1]] are the values of data[] in ascending order.
This code I have right here sorts the data but it doesn't do it the way its supposed to be done. It needs to be this way because we are not using objects and the indices of different arrays need to correspond. I really cant figure out what to do to make it sort by indices. Any help will be greatly appreciated.
void sort(float data[], int indx[], int len){
float temp;
//this for loop was just to declare the array of indices
//as it is passed in empty
for (int i = 0; i < len; i++){
indx[i] = i;
}
for (int i = 0; i < len - 1; i++){
for (int j = 0; j < len - 1; j++){
if (data[j] > data[j+1]){
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
}
Try this instead:
void sort(float data[], int indx[], int len) {
float temp;
for (int i = 0; i < len; i++) {
indx[i] = i;
}
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 2; j++) {
if (data[indx[j]] > data[indx[j+1]]) {
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
}
}
}
By the way... there are certain optimizations you can to to your bubble sort method. Remember that each pass requires one test less, since one element gets stuck in its definitive position. This helps a lot when it comes to performance, if you have to sort long lists.