Why isn't my string array being sorted correctly in c++?

111 views Asked by At

Here is my code and output.

I essentially use selection sort as my algorithm.

#include <iostream>
using namespace std;
void stringSort(string array[], int size)
{
    string temp;
    int minIndex;
    for(int count=0;count<size-1; count++)
    {
        minIndex=count;
        for(int index=count+1;index<size;index++)
        {
            if(array[index]<=array[minIndex])
            {
                minIndex = index;
            }
            temp = array[count];
            array[count] = array[minIndex];
            array[minIndex] = temp;

        }
    }
}
int main()
{
    string name[] =
    {  "Los Angeles ",  "Boise",  "Chicago",  "New Orleans",  "Calais",  "Boston",  "Duluth",  "Amarillo, TX "};

    int numberOfCities;

    numberOfCities = 8;

    int i;
    stringSort(name, numberOfCities);

    for (i =0; i<numberOfCities; i++) {
        cout<< name[i]<<endl;
    }
    return 0;
}

Output in my Xcode

Amarillo, TX 
Boston
Boise
Calais
Duluth
Chicago
Los Angeles 
New Orleans

which is wrong because Chicago and Duluth should have been switched along with Boise + Boston. Everything else is fine. What gives?

1

There are 1 answers

0
aQuigs On BEST ANSWER

You're doing the swap in every iteration of the inner loop. With selection sort, the goal is to loop though the remainder of the array to find the minimum, then swap. You should only swap at most once per iteration of the outer loop.

Instead try this:

for(int count=0;count<size-1; count++)
{
    minIndex=count;
    for(int index=count+1;index<size;index++)
    {
        if(array[index]<=array[minIndex])
        {
            minIndex = index;
        }
    }
    temp = array[count];
    array[count] = array[minIndex];
    array[minIndex] = temp;
}