C++ 为什么不是';t我的字符串数组在c++;?
这是我的代码和输出 我基本上使用选择排序作为我的算法C++ 为什么不是';t我的字符串数组在c++;?,c++,string,sorting,selection-sort,C++,String,Sorting,Selection Sort,这是我的代码和输出 我基本上使用选择排序作为我的算法 #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
#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;
}
这是错误的,因为芝加哥和德卢斯应该和博伊西+波士顿一起交换。其他一切都很好。有什么好处 在内部循环的每次迭代中都要进行交换。使用选择排序,目标是循环遍历数组的其余部分以找到最小值,然后交换。每次外循环迭代最多只能交换一次 相反,请尝试以下方法:
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;
}
for(int count=0;count
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;
}