我的选择排序函数c ++出了什么问题?

时间:2017-04-21 04:20:45

标签: c++

void selectionSort (vector<string>& dictionary)
{
    string min;

    for (int i = 0; i < dictionary.size(); ++i)
    {
        for (int j = i + 1; j < dictionary.size(); ++j)
        {
            if (dictionary.at(j) < dictionary.at(i))
            {
                min = dictionary.at(j);
            }
        }

        swap(dictionary.at(i), min);
    }

    return;
}

我输入了5个输入:嘿,好的,所以,不,好吧

输出:不,好吧,没有

有人可以解释我的排序功能出错了吗?谢谢!

1 个答案:

答案 0 :(得分:1)

请改为尝试:

void selectionSort(vector<string>& dictionary)
{
    for (int i = 0; i < dictionary.size(); ++i)
    {
        int m = i;
        for (int j = i + 1; j < dictionary.size(); ++j)
        {
            if (dictionary[j] < dictionary[m])
                m = j;
        }
        if (m != i)
            swap(dictionary[i], dictionary[m]);
    }
}

基本上,当您的i-loop开始时,您认为m - 元素最小,然后在j-loop内,如果元素较小,则检查剩余元素。如果找到较小的元素,则更新m(而不是复制实际的字符串)。在循环结束时,检查m是否已更改i,如果是,则在im处交换元素。

Here's full example with your input,在提出问题时,建议他们提供类似的简单示例,以便轻松复制您的问题:

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <assert.h>

using namespace std;


void selectionSort(vector<string>& dictionary)
{
    for (int i = 0; i < dictionary.size(); ++i)
    {
        int m = i;
        for (int j = i + 1; j < dictionary.size(); ++j)
        {
            if (dictionary[j] < dictionary[m])
                m = j;
        }
        if (m != i)
            swap(dictionary[i], dictionary[m]);
    }
}

int main()
{
    vector<string> data{ "hey", "ok", "so", "no", "okay" };
    vector<string> data2 = data;
    selectionSort(data);
    std::sort(data2.begin(), data2.end());
    assert(equal(data.begin(), data.end(), data2.begin())); // verify that your sort matches what std::sort does
    for (const auto s : data)
        cout << s << ' ';
    cout << endl;
}

,输出为:

hey no ok okay so