Search code examples
c++arraysbubble-sortselection-sort

Dual selection sorting an array - honestly stumped


void dualSort(int [], double [], int);
int main()
{
    const int ARRAY_SIZE = 1000;            // Array size
    double accountNumbers[ARRAY_SIZE];      // Array with 1000 elements
    double accountBalances[ARRAY_SIZE];     // Loop counter variable
    int count = 0;                              // Input file stream object
    ifstream inputFile;

    // Open the file.
    inputFile.open("FinalNumbers.txt");

    // Read the numbers from the file into the array
    while (count < ARRAY_SIZE && inputFile >> accountNumbers[count] >> accountBalances[count] ) {
        count++;
    }

    inputFile.close();

    // Display the read data
    cout << "The bank account numbers are: " << endl;
    for (int count = 0; count < ARRAY_SIZE; count++) {
        cout << accountNumbers[count] << "\n" << accountBalances[count] << " " << endl;
    }

    void dualSort(int accountNumbers[], double accountBalances, int ARRAY_SIZE);



}

I am required to use the selection sort or bubble sort algorithm.

I have Bank Account Numbers that have to be correspondingly and ascending sorted with there Account Balance, all the data is read from a file.

After sorting the data I have to rewrite it into another file, which is the least of my worries.

So the question is how do I go about sorting my accountNumbers in ascending order along with their accountBalance following them.


Solution

  • You need to sort according to accountNumbers but apply every swap operation to both arrays.

    Here is the code using selection sort:

    void dualSort(int accountNumbers[], double accountBalances[], int ARRAY_SIZE)
    {
     int minIndex;
    
     for(int i = 0; i < ARRAY_SIZE - 1; i++)
     {
      minIndex = i;
    
      for(int j = i + 1; j < ARRAY_SIZE; j++)
      {
       if(accountNumbers[j] < accountNumbers[minIndex])
       {
        minIndex = j;
       }
      }
    
      swap(accountNumbers[i], accountNumbers[minIndex]);
      swap(accountBalances[i], accountBalances[minIndex]);
     }
    }