三种常见的排序方法[选择,冒泡,快速]

public class Main{
    public static void main(String[] args){
        Main t = new Main();
        // 选择排序
        int[] data = new int[]{1,5,3,4,2,1,6};
        t.selectSort(data);
        for (int i=0; i<data.length; i++){
            System.out.print(data[i] + " ");
        }
        System.out.println();
        // 冒泡排序
        data = new int[]{1,5,3,4,2,1,6};
        t.bubbleSort(data);
        for (int i=0; i<data.length; i++){
            System.out.print(data[i] + " ");
        }
        System.out.println();
        // 快速排序
        data = new int[]{1,5,3,4,2,1,6};
        t.qsort(data,0,data.length-1);
        for (int i=0; i<data.length; i++){
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }

    /**
     * 选择排序[小 -> 大]
     */
    public int[] selectSort(int[] data){
        if (data == null || data.length < 2){
            return data;
        }
        for (int i=0; i<data.length; i++){
            int min = i;
            for (int j=i+1; j<data.length; j++){
                if (data[min] > data[j]){
                    min = j;
                }
            }
            if (i != min){
                int tmp = data[i];
                data[i] = data[min];
                data[min] = tmp;
            }
        }
        return data;
    }
    /**
     * 冒泡排序[小 -> 大]
     */
    public int[] bubbleSort(int[] data){
        if (data == null || data.length < 2){
            return data;
        }
        // 最多扫描 [0,length-2]趟
        int size = data.length - 2;
        boolean exchange = false;
        for (int i=0; i<=size; i++){
            exchange = false;
            for (int j=data.length-1; j>i; j--){
                if (data[j] < data[j-1]){
                    int tmp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = tmp;
                    exchange = true;
                }                
            }
            if (!exchange){
                break;
            }
        }
        return data;
    }
    /**
     * 快速排序
     */
    public int[] qsort(int[] data,int low,int high){
        if (low < high){
            // 分区
            int center = partition(data,low,high);
            // 对左边排序
            qsort(data,low,center-1);
            // 对右边排序
            qsort(data,center+1,high);
        }
        return data;
    }
    /**
     * 分区
     */
    public int partition(int[] data,int low,int high){
        int key = data[low];
        while(low < high){
            // 从右边找一个小于key的值
            while(low < high && key <= data[high]){
                --high;
            }
            data[low] = data[high];
            // 从左边找一个大于key的值
            while (low < high && data[low] <= key){
                ++low;
            }
            data[high] = data[low];
        }
        data[low] = key;
        return low;
    }
}

 

你可能感兴趣的:(J#,Exchange)