面试--排序(75)

来源:互联网 发布:宝鸡文理学院网络课程 编辑:程序博客网 时间:2024/06/04 20:09
public class BubbleQuickSort {    public void bubbleSort() {        int a[] = {49, 28, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 2, 62, 99, 56, 17, 18, 23, 34, 15, 23, 53, 51};        int temp = 0;        for (int i = 0; i < a.length; i++) {            for (int j = 0; j < a.length - i - 1; j++) {                if (a[j] > a[j + 1]) {                    temp = a[j];                    a[j] = a[j + 1];                    a[j + 1] = temp;                }            }        }        for (int i = 0; i < a.length; i++) {            System.out.print(" " + a[i]);        }    }    public void quickSort() {        int a[] = {49, 28, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 2, 62, 99, 56, 17, 18, 23, 34, 15, 23, 53, 51};        quick(a);        for (int i = 0; i < a.length; i++) {            System.out.print(" " + a[i]);        }    }    private void quick(int[] a) {        if (a.length > 0) {            _quickSort(a, 0, a.length - 1);        }    }    private void _quickSort(int[] list, int low, int high) {        if (low < high) {            int middle = getMiddle(list, low, high);//将list一分为二            _quickSort(list, low, middle - 1);            _quickSort(list, middle + 1, high);        }    }    private int getMiddle(int[] list, int low, int high) {        int tmp = list[low];//数组的第一个作为中轴        while (low < high) {            while (low < high && list[high] >= tmp) {                high--;            }            list[low] = list[high];//比中轴小的记录移动到低端            while (low < high && list[low] <= tmp) {                low++;            }            list[high] = list[low];        }        list[high]  = tmp;        return high;    }    public static void main(String[] args) {        new BubbleQuickSort().bubbleSort();        System.out.println("\r\n");        new BubbleQuickSort().quickSort(); //非递归使用  栈数据结构    }}
0 0