gpt4 book ai didi

c++ - 冒泡排序问题 C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:01 26 4
gpt4 key购买 nike

使用 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)但您仍然打印出传递/数组。最简单的解决方法是将循环调整为:

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

关于c++ - 冒泡排序问题 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com