【问题标题】:Why isn't my string array being sorted correctly in c++?为什么我的字符串数组没有在 C++ 中正确排序?
【发布时间】:2015-01-13 04:22:13
【问题描述】:

这是我的代码和输出。

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

#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

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

【问题讨论】:

    标签: c++ string sorting selection-sort


    【解决方案1】:

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

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多