2017-03-16 5 views
1

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

미안 해요, 난 그냥 올바른 방향으로 몇 가지만을 찾으려하고,이 섹시한 문제가되지 않습니다 알고있다.

답변

0

귀하의 오류는 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 
+0

는 설명과 예를 들어 주셔서 감사합니다! 두 가지 모두를 살펴 보는 것이 도움이됩니다. 건배! – McBraunie