C ++为几乎相同的代码提供不同的输出

时间:2016-11-02 05:09:30

标签: c++ algorithm sorting quicksort

我有一些书被洗牌,他们的话也被洗牌了。我想使用quicksort算法对它们进行排序。我对线条进行了排序,效果很好。然后我试着像这样排序每一行;

for each (Line l in lines) {
    srand(255);
    l.quicksort(0, l.words.size() - 1);
    for each (Word w in l.words)
        cout << w.content << " ";
    cout << endl;
}

srand part是因为我使用的是随机快速排序。这个循环给了我正确的结果。但是,当我试图像这样再写一次时;

for each (Line l in lines) {
    for each (Word w in l.words)
        cout << w.content << " ";
    cout << endl;
}

它给出的输出就像我没有调用quicksort函数一样。它是相同的代码,缺少一行。为什么会这样?

线类:

#include<iostream>
#include<vector>
#include "word.h"
using namespace std;

class Line {
public:
    vector<Word> words;
    Line(string&, string&);
    void quicksort(int, int);
private:
    int partition(int, int);
    void swap(int, int);
};

Line::Line(string& _words, string& orders) {
    // Reading words and orders, it works well.
}

void Line::quicksort(int p, int r) {
    if (p < r) {
        int q = partition(p, r);
        quicksort(p, q - 1);
        quicksort(q + 1, r);
    }
}

int Line::partition(int p, int r) {
    int random = rand() % (r - p + 1) + p;
    swap(r, random);
    int x = words[r].order;
    int i = p - 1;
    for (int j = p; j < r; j++)
        if (words[j].order <= x) {
            i++;
            swap(i, j);
        }
    swap(i + 1, r);
    return i + 1;
}

void Line::swap(int i, int j) {
    if (i != j) {
        Word temp = words[j];
        words[j] = words[i];
        words[i] = temp;
    }
}

1 个答案:

答案 0 :(得分:2)

您对本地副本进行排序,而不是按引用进行迭代:

srand(255); // Call it only once (probably in main)
for (Line& l : lines) {
    l.quicksort(0, l.words.size() - 1);
    for (const Word& w : l.words)
        std::cout << w.content << " ";
    std::cout << std::endl;
}
// Second loop
for (const Line& l : lines) {
    for (const Word& w : l.words)
        std::cout << w.content << " ";
    std::cout << std::endl;
}