冒泡排序不会正确排序或输出数组值

时间:2014-11-12 00:22:31

标签: c++

我有一个程序,它接受至少三个分数,最多三十个分数并将它们存储在一个数组中。我试图在一个函数中使用冒泡排序,该函数按升序对用户输入的值进行排序。排序不是按升序输出值,这是我过去一小时试图解决的问题。我试图修复的代码部分位于" sortAscending。"

#include <iostream>
#include <iomanip>

using namespace std;

void programInfo();
void inputList(double arr[], int &count);
void printList(double arr[], int n, int &count);
void sortAscending(double arr[], int n, int &count);

int main()
{
    double endProgram = 0;
    const int size = 30;
    double arr[size];
    int count = 0;
    int n = 0;
    while(endProgram != -1 || endProgram != -1.0)
    {
        programInfo();
        inputList(arr, count);
        printList(arr, n, count);
        sortAscending(arr, n, count);
        cout << "\n";
        cout << "Run program again? Enter -1 or -1.0 to end program."<< endl;
        cin >> endProgram;
            if (endProgram == -1 || endProgram == -1.0)
            {
                cout << "Thank you for using my program." << endl;
            }
    }
}

void programInfo()
{
     cout << "Statistical Calculator." << endl;
     cout << "Please follow instructions carefully." << endl;
     cout << "Enter one value at a time up to 30 values." << endl;
     cout << "You must enter valid data or program will not work." << endl;
     cout << "Enter -1 to signal end of data (-1 or -1.0)" << endl;
}

void inputList(double arr[], int &count)
{
    count = 0;
    char answer;
    cout <<"Input at least three values minimum, thirty values maximum." << endl;
    while (count < 30)
    {
        cout <<"Please enter a value." << endl;
        cin >> arr[count];
        count++;
        if (count == 3)
        {
            cout << "You have entered the minimum amount of values necessary." << endl; 
            cout << "Do you want to stop inputting values? (y/n)" << endl;
            cin >> answer;
            if (answer == 'y')
            {
                break;
            }
        }
    }
}

void printList(double arr[], int n, int &count)
{

    cout <<"Here is the list of values entered:" << endl;
    for (n = 0; n < count; n++)
        {
            cout << setw(8) << arr[n];
        }
}

void sortAscending(double arr[], int n, int &count)
{
    double temp;
    for (n = 0; n < count; n++)
    {
        for (int i = 0; i < count - 1; i++)
        {
            if(arr[i] < arr[n])
               {
                   temp = arr[n];
                   arr[n] = arr[i];
                   arr[i] = temp;
               }
            cout << arr[n] << endl;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

嗨你的问题是,在冒泡排序中你不应该将n与i进行比较,即插入排序,你必须将i与i + 1进行比较,这就是为什么循环中的条件是i&lt;计数1。

同样在消化时你必须在双循环之外打印数组,并使用另一个循环。

希望有所帮助。

for (int n = 0; n < count; n++)
{
  for (int i = 0; i < count - 1; i++)
  {
    if(arr[i] < arr[i+1])
    {
      temp = arr[i];
      arr[i] = arr[i+1];
      arr[i+1] = temp;
    }

  }
}
for(int i = 0; i < count; i ++){
  cout<<arr[i]<<" ";
}

答案 1 :(得分:0)

看起来您在排序过程中而不是在排序过程中输出值。我会从那里删除cout,然后遍历数组在他们进行排序后进行打印。