冒泡排序问题C ++

时间:2017-03-16 02:15:16

标签: c++ bubble-sort

使用C ++,我使用冒泡排序(升序)进行排序,程序似乎正在运行,但是我将最终传递作为重复值。我是编程新手,并且无法弄清楚如何纠正这个问题。有什么建议?

我的代码是:

#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
system("color 02");

HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);

string hyphen;
const string progTitle = "Array Sorting Program";
const int numHyphens = 70;

hyphen.assign(numHyphens, '-');

const int size = 8;

int values[size] = { 21, 16, 23, 18, 17, 22, 20, 19 };

cout << hyphen << endl;
cout << "                        " << progTitle << endl;
cout << hyphen << endl;

cout << "\n Array 1 before sorting:   \n" << endl;

printArray(values, size);

cin.ignore(cin.rdbuf()->in_avail());
cout << "\n Press 'Enter' to proceed to sorting Array 1\n";
cin.get();

cout << "\n Sorted ascending:   \n" << endl;
sortArrayAscending(values, size);

cin.ignore(cin.rdbuf()->in_avail());
cout << "\n\n\n\nPress only the 'Enter' key to exit program: ";
cin.get();
}

void sortArrayAscending(int *array, int size)
{
const int regTextColor = 2;
const int swapTextColorChange = 4;

HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);

int temp;
bool swapTookPlace;
int pass = 0;

do
{
    swapTookPlace = false;
    for (int count = 0; count < (size - 1); count++)
    {

        if (array[count] > array[count + 1])
        {
            swapTookPlace = true;
            temp = array[count];
            array[count] = array[count + 1];
            array[count + 1] = temp;
        }
    }
    cout << " Pass #" << (pass + 1) << ": ";
    pass += 1;
    printArray(&array[0], size);
 } while (swapTookPlace);
}

void printArray(int *array, int size)
{
for (int count = 0; count < size; ++count)
    cout << " " << array[count] << "   ";
cout << endl;
}

对不起,我知道这不是一个性感问题,我只是希望能找到正确方向的一些指示。

1 个答案:

答案 0 :(得分:0)

您的错误在City逻辑中。

在第四次传递时,do{ ... } while(swapTookPlace)swapTookPlace(因为确实发生了交换),因此您再次重复true循环。

在第五次迭代中,没有发生交换(do while),但您仍然打印出传递/数组。最简单的解决方法是将循环调整为:

swapTookPlace == false

输出:

do
{
    swapTookPlace = false;

    for (int count = 0; count < (size - 1); count++)
    {
        if(array[count] > array[count + 1])
        {
            swapTookPlace = true;
            temp = array[count];
            array[count] = array[count + 1];
            array[count + 1] = temp;
        }
    }

    if(swapTookPlace)
    {
        cout << " Pass #" << (pass + 1) << ": ";
        pass += 1;
        printArray(&array[0], size);
    }

 } while(swapTookPlace);