2016-12-02 13 views
-4

バブルソートをしようとしていますが、自分のコードで何が起こっているのか分かりません。私はnoobですので、私が書いたコードは明らかです^バブルソート論理エラー?

main() { 
     int a[5], i, j, smallest, temp; 
     cout << "Enter 5 numbers: " << endl; 
     for (i = 0; i <= 4; i++) { 
      cin >> a[i]; 
     } 

    for (i = 0; i <=4; i++) { 
     smallest = a[i]; 
     for (j = 1; j <= 4; j++) { 
      if (smallest > a[j]) { 
       temp = a[i]; 
       a[i] = a[j]; 
       a[j] = temp; 
      } 
     } 
    } 


     cout << endl << endl; 

     for (i = 0; i <= 4; i++) { 
      cout << a[i] << endl; 
     } 
     system("pause"); 
    } 

何か答えが高く評価されます。ありがとう!

+2

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

+0

これはバブルソートではなく、選択ソートです。 – GoodDeeds

答えて

1

あなたのbubblesortは、ほとんど選択の並べ替えのようです。 Bubblesortはアイテムのペアを調べ、必要に応じてスワップします。選択ソートは、残りの配列の中で最も小さい項目を探してからスワップします。

#include <iostream> 
#include <utility> 

using std::cin; 
using std::cout; 
using std::endl; 
using std::swap; 

void bubblesort(int a[5]) 
{ 
    bool swapped = true; 
    while (swapped) 
    { 
     swapped = false; 
     for (int i = 0; i < 4; i++) 
     { 
      if (a[i] > a[i + 1]) 
      { 
       swap(a[i], a[i + 1]); 
       swapped = true; 
      } 
     } 
    } 
} 

void selectionSort(int a[5]) 
{ 
    for (int i = 0; i < 4; i++) 
    { 
     int smallest = i; 
     for (int j = smallest; j < 5; j++) 
     { 
      if (a[smallest] > a[j]) 
      { 
       smallest = j; 
      } 
     } 
     if (smallest != i) 
     { 
      swap(a[i], a[smallest]); 
     } 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    int a[5]; 
    cout << "Enter 5 numbers: " << endl; 
    for (int i = 0; i < 5; i++) 
    { 
     cin >> a[i]; 
    } 

    //selectionSort(a); 
    bubblesort(a); 

    cout << endl << endl; 

    for (int i = 0; i <= 4; i++) { 
     cout << a[i] << endl; 
    } 
}