java实现4种内部排序

两种插入类排序:

直接插入排序:

  public static int[] insertSort(int[] arr){
      int i,j,temp;
      int n=arr.length;
      for(i=1; i<n; i++){
          temp=arr[i];
          j=i-1;
          while(j>=0&&temp<arr[j]){
              arr[j+1] = arr[j];
              --j;
          }
          arr[j+1] = temp;
      }
      return arr;
  }

二分插入排序:

public static int[] binarySort(int arr[]){
     int n = arr.length; int i, j,temp,low,mid,high; for(i=1; i<n; i++){ temp=arr[i]; low=0; high=i-1; while(low<=high){ mid=(low+high)/2; if(arr[mid]>temp) high=mid-1; else low = mid+1; } for(j=i-1;j>=high+1; --j) arr[j+1]=arr[j]; arr[low]=temp; } return arr; }

两种交换类排序:

冒泡排序:

public static int[] bubbleSort(int[] arr){
        int temp;
int n = arr.length; boolean flag = false; for(int i=n-1; i>=1; i--){ for(int j=1; j<=i; j++){ if(arr[j-1]>arr[j]){ temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; flag=true; } } if(!flag) return arr; } return arr; }

快速排序:

ublic static int[] quickSort(int arr[], int low, int high){       
        if(low<high){
            int temp = arr[low];
            int i = low, j = high;
            while(i!=j){
                while(i<j && arr[j]>=temp) --j;
                if(i<j){
                    arr[i] = arr[j];
                    i++;
                }
                while(i<j && arr[i]<temp) ++i;
                if(i<j){
                    arr[j]=arr[i];
                    j--;
                }
            }
        arr[i] = temp;
        quickSort(arr, low, i-1);
        quickSort(arr, i+1, high);
        return arr;
        }
        return arr;
    }

  

猜你喜欢

转载自www.cnblogs.com/sjxbg/p/11226319.html
今日推荐