gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:34:36 24 4
gpt4 key购买 nike

这是我的代码和输出。

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

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

关于c++ - 为什么我的字符串数组没有在 C++ 中正确排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26952652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com