四种常见排序

一、选择排序

package testCode;

public class Run {
    public static void main(String[] args) {  
    int[] arr = {5,4,8,9};
    selectSort(arr);
    for(int i=0;iout.print(arr[i]+" ");
    }
    }

    private static void selectSort(int[] arr) {
        // TODO Auto-generated method stub
        int n = arr.length;
        int tmp =0;
        int flag = 0;
        for(int i=0;ifor(int j=i+1;jif(arr[j]if(flag!=i){
                arr[flag] = arr[i];
                arr[i] = tmp;
            }
        }

    }  
}

结果:

4 5 8 9 

二、插入排序

package testCode;

public class Run {
    public static void main(String[] args) {  
    int[] arr = {5,4,8,9};
    insertSort(arr);
    for(int i=0;iout.print(arr[i]+" ");
    }
    }

    private static void insertSort(int[] arr) {
        // TODO Auto-generated method stub
        int temp=0;
        int j =0;
        if(arr!=null){
            for(int i=1;iif(arr[j-1]>temp){
                    while(j>=1&&arr[j-1]>temp){
                        arr[j] = arr[j-1];
                        j--;
                    }
                }
                arr[j] = temp;
            }
        }

    }  
}

运行结果:

4 5 8 9 

注意:

  1. 一个for循环+while循环
  2. while(j>=1&&arr[j-1]>temp)终止条件
  3. 两个变量保存arr[i]以及下标信息

    三、归并排序 MergeSort

package testCode;

public class Run {
    public static void main(String[] args) {  
    int[] arr = {5,4,8,9};
    mergeSort(arr,0,arr.length-1);
    for(int i=0;iout.print(arr[i]+" ");
    }
    }

    private static void mergeSort(int[] arr,int start,int end) {
        // TODO Auto-generated method stub
        if(startint mid = (start+end)>>1;
            mergeSort(arr,start,mid);
            mergeSort(arr,mid+1,end);
            merge(arr,start,mid,end);
        }

    }

    private static void merge(int[] arr, int left,int mid, int right) {
        // TODO Auto-generated method stub
        int i = left;
        int j = mid+1;
        int k=0;
        int[] tmp = new int[arr.length];
        while(i<=mid&&j<=right){//终止条件有等号,闭区间
            if(arr[i]<=arr[j]){
                tmp[k++] = arr[i++];
            }
            else{
                tmp[k++] = arr[j++];
            }
        }
        while(i<=mid){
            tmp[k++] = arr[i++];
        }
        while(j<=right){
            tmp[k++] = arr[j++];
        }
        for(int m = 0;m//起始位置为left+m
        }

    }  
}

运行结果:

4 5 8 9 

三个while(..)循环

四、快排

package testCode;

public class Run {
    public static void main(String[] args) {  
    int[] arr = {5,4,8,9};
    quickSort(arr,0,arr.length-1);
    for(int i=0;iout.print(arr[i]+" ");
    }
    }

    private static void quickSort(int[] arr,int start,int end) {
        // TODO Auto-generated method stub
        int i=start;
        int j =end;
        int index = arr[i];
        if(i>=j){
            return ;
        }
        while(iwhile(i=index){
                j--;
            }
            if(iwhile(iif(i1,end);
    }

}

运行结果:

4 5 8 9 

你可能感兴趣的:(java)