[英]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)
邏輯中。
在第四次傳遞時, swapTookPlace
為true
(因為確實發生了交換),因此您再次重復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.