【问题标题】:c++ sorting by making array of indicesc++ 通过创建索引数组进行排序
【发布时间】:2016-06-04 11:15:51
【问题描述】:

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

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


     }
    }
}

【问题讨论】:

  • 如果数据乱序,不交换数据,而是交换索引数组。对我来说似乎很简单。如果您使用铅笔和纸来解决这个问题,您应该会从概念上看到正在做的事情。
  • 谢谢!我不知道为什么这让我难了这么久。现在可以了。
  • 注意 - 比较应该是 |如果 (数据[indx[j]] > 数据[indx[j+1]]) | .
  • @rcgldr 非常正确。
  • @rcgldr 好的,也谢谢你。它适用于我的原始数据集,但一旦我用其他东西进行测试,它就不起作用了。现在它在更改比较后执行。我很感激。

标签: c++ sorting indices


【解决方案1】:

试试这个:

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

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2023-03-22
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多