用int

时间:2018-01-19 04:46:12

标签: c++ arrays sorting

#include <iostream>
using namespace std;

void selectionSort (float arr[], int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = i+1; j < n; ++j) {
            if (arr[i] > arr[j]) {
                arr[i] = arr[i] + arr[j];
                arr[j] = arr[i] - arr[j];
                arr[i] = arr[i] - arr[j];
            }


        }

    }
}


int main() {
    int n = 3;

    string name[n];
    float arr[n];

    for (int i = 0; i < n; i++) {
        cout << "Name of runner " << i+1 << ": ";
        cin >> name[i];

        cout << "Runner " << i+1 << "'s finishing time: ";
        cin >> arr[i];
        cout << endl;
    }


    selectionSort(arr, n);

    cout << "1st place: " << name[0] << "\t" << arr[0] << endl;
    cout << "2nd place: " << name[1] << "\t" << arr[1] << endl;
    cout << "3rd place: " << name[2] << "\t" << arr[2] << endl;
}

因此,当我输入姓名和结束时间时,只有完成时间按照从最快到最慢的顺序排序。我需要帮助让跑步者的名字与完成的时间相匹配。

3 个答案:

答案 0 :(得分:4)

而不是两个占位符名称[3]和arr [3]尝试使用如下对的向量:

std::sort(RunnerPairVector.begin(), RunnerPairVector.end());

然后你可以使用sort来根据完成时间对你的对进行排序,如下所示

{{1}}

答案 1 :(得分:0)

对名称进行排序也与其完成时间相对应。

#include <iostream>
using namespace std;

// Pass name array also to access it..
void selectionSort (string name[], float arr[], int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = i+1; j < n; ++j) {
            if (arr[i] > arr[j]) {
                arr[i] = arr[i] + arr[j];
                arr[j] = arr[i] - arr[j];
                arr[i] = arr[i] - arr[j];
                // Swap names also corresponding to their finishing times.
                string temp = name[i];
                name[i] = name[j];
                name[j] = temp;
            }


        }

    }
}


int main() {
    int n = 3;

    string name[n];
    float arr[n];

    for (int i = 0; i < n; i++) {
        cout << "Name of runner " << i+1 << ": ";
        cin >> name[i];

        cout << "Runner " << i+1 << "'s finishing time: ";
        cin >> arr[i];
        cout << endl;
    }


    selectionSort(name, arr, n);

    cout << "1st place: " << name[0] << "\t" << arr[0] << endl;
    cout << "2nd place: " << name[1] << "\t" << arr[1] << endl;
    cout << "3rd place: " << name[2] << "\t" << arr[2] << endl;
}

答案 2 :(得分:0)

你在做错的是你正在对时间数组进行排序,但没有对名称数组进行相应的更改。所以你也可以传递名字数组和时间数组,当你交换时间时,同时交换相应的名字。像这样......

void selectionSort(float arr[], string name[], int n) {
  int i, j;
  string temp;
  for (i = 0; i < n; ++i) {
    for (j = i + 1; j < n; ++j) {
      if (arr[i] > arr[j]) {
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
        //name swapping
        temp = name[i];
        name[i] = name[j];
        name[j] = temp;
      }

    }

  }
}

还有一件事是你的函数没有返回这个更改的数组。所以要么你返回这个更改过的数组,要么让这个时间和名称数组全局可访问。