2016-06-21 45 views
0

/*這個函數在main中被調用。它用於冒泡排序*/爲什麼我在使用遞歸的冒泡排序代碼中出現運行時錯誤

void sort(int a[], int n)  //parameters passed:array to be sorted, no.of 
          // elements in the array                            
{ int count=0; 
    for(int i=0;i<n-1;i++) 
    { if(a[i+1]<a[i])    // if the next element is greater in value 
     { 
     int temp=a[i+1];    // the numbers 
     a[i+1]=a[i];     // are 
     a[i]=temp;      // swapped;i want increasing order 
        } 
    else count++; 
         } 
     if(count==n) 
     return; 
     else sort(a,n); 
     return; } 

回答

1

其與遞歸的基本情況有問題..更改像這樣

public static void sort(int[] a, int n){ 

     int count=0; 

     for(int i=0;i<n-1;i++){ 
      if(a[i+1]<a[i])    
      { 
       int temp=a[i+1];    
       a[i+1]=a[i];     
       a[i]=temp; 
       count++; 
      } 
     } 

     if(count!=0) 
      sort(a,n); 


    }` 

如果我們在主調用它,

public static void main(String[] args) { 
     int[] arr = {20,15,25,32,1,90,35,61}; 
     sort(arr,8); 
     System.out.println(""); 

     for(int i = 0;i<arr.length;i++){ 
      System.out.print(arr[i] + " "); 
     } 
    } 

輸出是gonnna be,

1 15 20 25 32 35 61 90