排序算法代码中的未知问题

时间:2014-08-04 17:27:36

标签: c++ algorithm bubble-sort

我是初学者。这可能听起来很愚蠢,因为它是一个简单的算法。下面的程序编译成功,但是当我运行它时不打印排序的数组。代码工作正常直到排序算法。然后它不会打印排序的数组。我究竟做错了什么?代码:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int n, i, k = -1;
    cout << "Enter the number of elements: ";
    cin >> n;

    int arr[n];
    cout << "Enter the elements to be sorted: ";
    for (i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    cout << "The unsorted array: \n";

    for(i = 0; i < n; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    //BubbleSort.

    for(int e = n-1; e > 0; --e)
    {
        for (i = 0; i > e; ++i)
        {
            if (arr[i] > arr[i + 1]) {
                arr[i] = k;
                arr[i] = arr[i + 1];
                arr[i + 1] = k;
            }
        }
    }

    cout << "The sorted list: ";

    for (int x = 0; x > n; ++x)
    {
        cout << arr[x] << ' ';
    }

    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:4)

&#34;初学者&#34; 错误不是真的吗?

更好地使用std::cout或调试器来指出错误/缺陷

负责比较和作业

  • arr[i] = k;应为k = arr[i] ;

  • for (i = 0; i > e; ++i)应为for (i = 0; i < e; ++i)

  • for (int x = 0; x > n; ++x)应为for (int x = 0; x < n; ++x)

答案 1 :(得分:3)

建议重读一篇关于C ++和编程的教程,一些错误是基本错误:

  • 比较运算符
  • 分配

有问题的代码:

for (int e = n - 1; e > 0; --e) {
    for (i = 0; i < e; ++i) { // << change here, i > e   ->   i < e you are incrementing
        if (arr[i] > arr[i + 1]) {
            k = arr[i];            // change here, you save in a tmp variable to swap values
            arr[i] = arr[i + 1];
            arr[i + 1] = k;
        }
    }
}

cout << "The sorted list: ";

for (int x = 0; x < n; ++x) { // change here x > n    ->    x < n      same as before.
    cout << arr[x] << ' ';
}