2015-10-05 126 views
0

//你好,我只是寫這個程序,我不知道爲什麼我的輸出不能正確打印。答案應該是1,2,3,4,6,但它會打印2,1,4,3,6。謝謝一堆。泡泡排序程序(錯誤輸出)

#include <iostream> 
using namespace std; 

void bubblesort(int A[], int n) 

{ 

for (int i =1; i< n-1; i++) 

{ 

for (int j =0; j< n-i-1; j++) 
    { 

if(A[i] > A[i+1]) 
     { 
      swap(A[i], A[i+1]); 
     } 
    } 
} 
} 

int main() 
{ 
int A[] = {2,4,1,6,3}; 
bubblesort(A,5); 
    for(int i =0; i<5; i++) 
    { 
     cout<<A[i]<<" "; 
    } 
} 
+0

按照您的代碼手動執行該算法,您將理解。我有什麼問題,而且你不需要j。 – Mel

回答

0

你不與變量j正確和交換書面外環爲後續代碼。

#include <iostream> 

using namespace std; 



//Bubble Sort 

void bubble_sort (int arr[], int n) 

{ 

    for (int i = 0; i < n; ++i) 

    for (int j = 0; j < n - i - 1; ++j) 

     if (arr[j] > arr[j + 1]) 

    { 

     int temp = arr[j]; 

     arr[j] = arr[j + 1]; 

     arr[j + 1] = temp; 

     } 

    }  



//Driver Function 

int main() 

{ 

    int input_ar[] = {10, 50, 21, 2, 6, 66, 802, 75, 24, 170}; 

    int n = sizeof (input_ar)/sizeof (input_ar[0]); 

    bubble_sort (input_ar, n); 

    cout << "Sorted Array : " << endl; 

    for (int i = 0; i < n; ++i) 

    cout << input_ar[i] << " "; 

    return 0; 

}