Garmaine Staff asked 4 months ago

I've been working with data from a file and keeping them paired together. I need to sort the data alphabetically while keeping them paired together at the same time. I have successfully done it with bubble sort here:

     for (int i = 1; i <= count; i++)
     {
         for (int j = 0; j < count - 1; j++)
         {
             if (email [j].compareToIgnoreCase (email [j + 1]) > 0)
             {
                 temp1 = email [j];
                 email [j] = email [j + 1];
                 email [j + 1] = temp1;

                 temp2 = fname [j];
                 fname [j] = fname [j + 1];
                 fname [j + 1] = temp2;

                 temp3 = lname [j];
                 lname [j] = lname [j + 1];
                 lname [j + 1] = temp3;

                 temp4 = city [j];
                 city [j] = city [j + 1];
                 city [j + 1] = temp4;

                 temp5 = age [j];
                 age [j] = age [j + 1];
                 age [j + 1] = temp5;
             }
         }
     }
}

I get an output like this: Email: bobbarley@gmail.com First Name: Bob Last Name: Barley City: Vancouver Age: 13 Email: felixfixed@gmail.com First Name: Felix Last Name: Fixed City: Boston Age: 24 Email: joejake@gmail.com First Name: Joe Last Name: Jake City: Toronto Age: 32

On the other hand I have an insertion sort, but I can't keep the data together. Here is my code:

for (int i = 1; i < count; i++)
    {
        String current = fname [i];
        int j = i - 1;

        while (j >= 0 && current.compareToIgnoreCase (fname [j]) < 0)
        {
            fname [j + 1] = fname [j];
            j--;
        }
        fname [j + 1] = current;
    }

With this part, I get this output:

First Name: Bob Last Name: Jake City: Toronto Age: 32 Email: joejake@gmail.com First Name: Felix Last Name: Barley City: Vancouver Age: 13 Email: bobbarley@gmail.com First Name: Joe Last Name: Fixed City: Boston Age: 24 Email: felixfixed@gmail.com