为什么我的字符串数组在 c++ 中没有正确排序?
Why isn't my string array being sorted correctly in c++?
这是我的代码和输出。
我基本上使用选择排序作为我的算法。
#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 选择排序字符串数组
- C 排序字符串的动态阵列 - 排序不起作用
- C++:使用 LSD 基数排序字符串排序崩溃
- 标准::排序 C 字符串的比较函数
- 使用最小运算将给定字符串转换为排序字符串
- C++ - 链表插入排序(字符串元素)
- 分段错误(核心转储)排序字符串数组错误
- 比较函数用于排序字符串的矢量(每个字符串都是一个数字)C++
- std::mutiset vs std::vector,用于读取排序字符串并将其写入文件
- 按字母顺序快速排序字符串矢量
- C++按字母顺序排序字符串
- 按长度排序字符串数组
- 我如何使用c++库函数或STL排序字符串
- 首先按字符排序字符串
- 如何按ASCII顺序排序字符串
- 按字母顺序排序字符串数组
- 按降序排序字符串