Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么不是';t我的字符串数组在c++;?_C++_String_Sorting_Selection Sort - Fatal编程技术网

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