2016-06-21 4 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

1 15 20 25 32 35 61 90 
あります
関連する問題