为什么我在使用递归的冒泡排序代码中出现运行时错误

时间:2016-06-21 15:47:57

标签: function recursion runtime-error

/ *在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 个答案:

答案 0 :(得分: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