繁体   English   中英

冒泡排序问题C ++

[英]Bubble Sort Issues C++

使用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;
}

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

您的错误在do{ ... } while(swapTookPlace)逻辑中。

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

在第五次迭代中,没有发生交换( swapTookPlace == false ),但您仍然打印出pass / array。 最简单的解决方法是将循环调整为:

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);

输出:

Pass #1:  16    21    18    17    22    20    19    23
Pass #2:  16    18    17    21    20    19    22    23
Pass #3:  16    17    18    20    19    21    22    23
Pass #4:  16    17    18    19    20    21    22    23

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM