【问题标题】:C++ Bubble Sort Ascending order - does not sort all elementsC++ 冒泡排序升序 - 不对所有元素进行排序
【发布时间】:2017-02-17 05:25:17
【问题描述】:

我必须编写一个程序,提示用户输入要读入的整数个数。然后提示用户输入这些整数。然后它将整数存储到一个向量中,并在冒泡排序过程中按升序打印排序值。 我的程序中的问题是,并非向量中的所有值都正确排序。这是我的代码:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> numbers;
    int nums;

    cout << "This program reads number of integers and store them into a vector."
        << "\nThen prints the values using Bubble Sort."; 
    cout << "\nEnter the size of the vector to be sorted using Bubble sort: ";
    cin >> nums;

    for (int i = 0; i < nums; i++)
    {
        int number;
        cout << "Enter a number: ";
        cin >> number;
        numbers.push_back(number);
    }
        for (int i = 0; i < (nums - 1); i++)
        {
            for (i = 1; i < nums; ++i)

            {
                for (int j = 0; j < (nums - j); ++j)
                    if (numbers[j]>numbers[j + 1]) // swapping element in if statement
                    {
                        int number = numbers[j];
                        numbers[j] = numbers[j + 1];
                        numbers[j + 1] = number;
                        bool swap = true;
                    }
            }

        // Displaying the sorted list
        cout << "\nSorted list in ascending order using Bubble Sort:\n";

        for (int a = 0; a < nums; a++) //Use for loop to print the array
        {
            cout << numbers[a] << " ";
        }

        system("pause");
        return 0;
    }
}

例如,我输入一个 8 个整数长向量和数字: 43 6 23 1 75 34 98 76

输出是: 1 6 23 43 75 35 98 76

所以看起来数字被正确存储到第 5 个整数的一半。

【问题讨论】:

  • j &lt; (nums - j) 由于这种奇怪的情况,您最里面的循环只查看了大约一半的元素。
  • 为什么你有 2 个使用 i 作为索引的 for 循环?
  • 三个嵌套的for 循环中的第二个忽略了外部循环。
  • @IgorTandetnik,非常感谢!它应该是 j
  • 只是为了让你的练习更有价值和 c++ish:你可以尝试实现一个在 ForwardIterators 上运行的 bubble_sort 函数并使用通用比较。

标签: c++ arrays sorting vector


【解决方案1】:

为了清楚起见,我做了一个外部的bubbleSort函数,下面是代码。我希望它可以帮助您了解它的工作原理。

#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;
using std::cin;
using std::cout;

void bubbleSort(vector<int>& arr)
{
    int n = arr.size();
    for(int i = 0; i < n-1; ++i)
    {
        for(int j = 0; j < n-i-1; ++j)
        {
            if(arr[j] > arr[j+1])
                std::swap(arr[j], arr[j+1]);
        }
    }
}

int main()
{
    int numOfElements;
    cin >> numOfElements;
    vector<int> arr(numOfElements);
    for(int i = 0; i < numOfElements; ++i)
        cin >> arr[i];
    bubbleSort(arr);

    for(auto elem : arr)
        cout << elem << " ";
}

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多