C ++通过制作索引数组进行排序

c++ sorting by making array of indices

我有一个项目要创建一个调度程序,其中一部分需要排序。我知道如何使用常规冒泡排序来做到这一点,但项目要求我这样做...

sort() — 对浮点数组数据[] 进行排序的函数,创建一个排序索引数组。 sort() 函数不对数据进行排序,而是填充数组 indx[] 以便 数据[indx[0]], 数据[indx[1]], ..., 数据[indx[NUM_EVENTS - 1]] 是按升序排列的 data[] 的值。

我这里的这段代码对数据进行了排序,但它并没有按照预期的方式进行。需要这样是因为我们没有使用对象,不同数组的索引需要对应。我真的不知道该怎么做才能按索引排序。任何帮助将不胜感激。

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;
        }


     }
    }
}

试试这个:

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;
            }
        }
    }

}

顺便说一句...您可以对冒泡排序方法进行某些优化。请记住,每次通过都需要少一次测试,因为一个元素会卡在其最终位置。如果您必须对长列表进行排序,这对性能有很大帮助。