【发布时间】:2017-08-08 18:00:28
【问题描述】:
我有一个程序可以打印出数组中冒泡排序的传递,并希望尝试添加显示(通过文本颜色更改)在每次传递时在数组中发生交换的位置的功能。到目前为止,我尝试过的所有内容要么更改所有文本颜色,要么不更改任何内容(如当前示例所示)。谁有想法?
#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <string>
using namespace std;
void sortArrayAscending(int *array, int size);
void printArray(int *array, int);
void printUnsortedArray(int *array, int size);
int main()
{
HANDLE a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(a, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
string hyphen;
const string progTitle = "Array Sorting Program";
const int numHyphens = 100;
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 This program will sort two identical arrays of numbers using a Bubble Sort"<< endl;
cout << "\n Array 1 -- Ascending Order: \n" << endl;
printUnsortedArray(values, size);
cout << 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;
if (swapTookPlace)
{
SetConsoleTextAttribute(screen, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
if (array[count] > array[count + 1])
{
SetConsoleTextAttribute(screen, swapTextColorChange);
}
if (pass < 9)
{
cout << fixed << setw(2) << " Pass # " << (pass + 1) << " : ";
pass += 1;
printArray(&array[0], size);
}
else if (pass >= 9)
{
cout << fixed << setw(2) << " 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;
}
void printUnsortedArray(int *array, int size)
{
cout << " Unsorted ";
for (int count = 0; count < size; ++count)
cout << " " << array[count] << " ";
cout << endl;
【问题讨论】:
标签: c++ arrays colors bubble-sort