简体   繁体   中英

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

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM