JAVA 数据结构与算法之————快速排序

JAVA 数据结构与算法之————快速排序

快速排序:

/*
* 快速排序的时间复杂度为O(nlogn), 空间复杂度为O(logn)
* */
public class QuickSort<E extends Comparable> {

    Swap<E> s = new Swap<>();
    /*一轮排序*/
    public int sort(E[] L, int low, int hight){
        E temp = L[low];
        while(low < hight){
            while(L[hight].compareTo(temp) > 0 && low < hight){
                hight--;
            }
            s.swap(L, low, hight);
            while(L[low].compareTo(temp) <= 0 && low < hight){
                low++;
            }
            s.swap(L, low, hight);
        }
//        L[low] = temp;
        return low;
    }

    /*快速排序*/
    public void quickSort(E[] L, int low, int hight){
        if(low < hight){
            int temp = sort(L, low, hight);
            quickSort(L, low, temp - 1);
            quickSort(L, temp + 1, hight);
        }
    }

    public static void main(String[] args) {
        QuickSort<Integer> quickSort = new QuickSort<>();
        Integer[] data = {2, 4, 6, 1, 8, 2, 0, 3, -1};
        quickSort.quickSort(data, 0, data.length - 1);
        System.out.println(Arrays.toString(data));
    }

}

swap方法:

public void swap(E[] data, int i, int j){
        E temp = data[i];
        data[i] = data[j];
        data[j] = temp;
    }

你可能感兴趣的:(JAVA,数据结构与算法)