jeudi 1 février 2018

Understanding a sort algorithm in C++

I'm having trouble with executing the code below. When the numbers are being swapped in the bottom, can someone explain the algorithm thoroughly? For example arr[I] = arr[I] + arr[j]. When I do the algorithm, I'm getting a different answer.

Thanks

#include <iostream>
using namespace std;

void raceSort(double arr[], string name[], int n);

int main() {
    int n = 3; //declare # of runners
    string name[n];
    double arr[n];

    cout << "Enter the names of three runners and their finishing times." << endl;
    cout << "Then I will tell you who came in first, second, and third." << endl;
    cout << endl;

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

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

    //call raceSort method
    raceSort(arr, name, n);


    //displays in order from fastest time to slowest
    cout << fixed;
    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;
}

// {17.3, 15.32, 11.32)
void raceSort(double arr[], string name[], int n) {
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] > arr[j]) {
                //swapping numbers in order
                arr[i] = arr[i] + arr[j];
                arr[j] = arr[i] - arr[j];
                arr[i] = arr[i] - arr[j];
                //swapping name in correspondence to time
                string temp = name[i];
                name[i] = name[j];
                name[j] = temp;
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire