2017-03-16 21 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)ロジックです。

4回目のパスでswapTookPlacetrue(スワップが行われたため)であるため、do whileループを再度繰り返します。

この5回目の繰り返しではスワップは行われませんが(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