算法笔记 - 数组与单链表快速排序(Java)

数组快速排序

public class QuickSort {
    private static final int COUNT = 1000000;
    private static final int ZONE = 200;

    public static void main(String[] args){
        Random rand = new Random();
        Integer[] array = new Integer[COUNT];
        for(int i=0;i=right) return;
        int i = left;
        int j = right;
        int key = array[(i+j)/2];
        while(i=key;j--);
            array[i] = array[j];

            for(;i

单链表快速排序

public class LinkedQuickSort {

    private static final int COUNT = 100000;
    private static final int ZONE = 200;

    public static void main(String[] args){
        Random rand = new Random();
        Node node = new Node(0);
        Node head = node;

        for(int i=0;ival){
                right.next = head;
                right = right.next;
            }else{
                middle.next = head;
                middle = middle.next;
            }
        }

        left.next = null;
        middle.next = null;
        right.next = null;
        return merge(quickSort(leftHead.next),middleHead.next,quickSort(rightHead.next));
    }

    private static Node merge(Node left, Node middle, Node right) {
        Node leftTail = findTail(left);
        Node middleTail = findTail(middle);
        middleTail.next = right;
        if(left!=null){
            leftTail.next = middle;
            return left;
        }else{
            return middle;
        }
    }

    private static Node findTail(Node node){
        Node tail = node;
        if(tail != null){
            while(tail.next!=null){
                tail = tail.next;
            }
        }
        return tail;
    }
}

class Node{
    int val;
    Node next;
    public Node(int val) {
        this.val = val;
    }
}

本文为作者kMacro原创,转载请注明来源:http://www.jianshu.com/p/c8ebc015a404。

你可能感兴趣的:(算法笔记 - 数组与单链表快速排序(Java))