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

标签 c++ sorting indices

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

sort() — 对 float 组数据[] 进行排序的函数,创建一个排序索引数组。 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;
            }
        }
    }

}

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

关于C++通过制作索引数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35563636/

相关文章:

python - pandas 中的逆向查找 : get ordered lists of row- and column-names

Python 通过跳过列表之间的值将值附加到空列表

c++ - 捕获和处理视频时出现性能问题

c++ - 如何使用 vector<pair<int,pair<int,int>>> 进行排序?

c++ - 如何在 C++ 中按字母顺序排序

java - 索引无法正确读取

java - h.264解析训练

c++ - 对大数组求和时出现错误结果

c++ - Pthread 在信号句柄中使用 pthread_cond_wait 阻塞

python - 在不导入任何模块的情况下以 min :sec, 格式对时间进行排序的有效方法是什么?