为什么我的字符串数组在 c++ 中没有正确排序?

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

本文关键字:排序 字符串 我的 数组 c++ 为什么      更新时间:2023-10-16

这是我的代码和输出。

我基本上使用选择排序作为我的算法。

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

在我的 Xcode 中输出

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

这是错误的,因为芝加哥和德卢斯应该与博伊西+波士顿一起切换。其他一切都很好。什么给?

你在内部循环的每次迭代中执行交换。使用选择排序时,目标是遍历数组的其余部分以找到最小值,然后交换。每次外循环迭代最多只交换一次。

相反,请尝试以下操作:

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