通过创建索引数组进行 C++ 排序

c++ sorting by making array of indices

本文关键字:C++ 排序 数组 创建 索引      更新时间:2023-10-16

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

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

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

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

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