泡沫排序问题C++
问题描述:
使用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)
逻辑。
第四次通过时,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);
输出:
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
谢谢你的解释和例子!有两个看看真的很有帮助。干杯! – McBraunie