单链表快排

不知道为什么,现在某些公司喜欢考单链表快排,有什么意思呢?没意思。

首先理解快排的思想,partition,递归。

代码里有注释,挺详细的了,自己验证逻辑应该没什么问题。

package leetcode.sort;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * 单链表快排
 * Created by blank on 2015-11-03 下午8:42.
 */
public class ListQuickSort {

    public static final int R = 50;

    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new FileInputStream("/Users/blank/IdeaProjects/LeetCode/src/main/java/leetcode/sort/input.in"));
        int[] arr = new int[R];
        for (int i = 0; i < R; i++) {
            arr[i] = new Random().nextInt(100);
        }
        System.out.println(Arrays.toString(arr));
        ListNode head = new ListNode(0);
        ListNode p = head;
        for (int i = 0; i < arr.length; i++) {
            ListNode node = new ListNode(arr[i]);
            p.next = node;
            p = p.next;
        }
        quickSort(head.next, null);
        head = head.next;
        while (head != null) {
            System.out.print(head);
            head = head.next;
        }
    }

    public static void quickSort(ListNode head, ListNode tail) {
        if (head != tail) {
            //以各部分第一个元素为pivot元素,然后划分左右
            ListNode pr = sort(head, tail);
            quickSort(head, pr);
            quickSort(pr.next, tail);
        }
    }

    private static ListNode sort(ListNode head, ListNode tail) {
        if (head == tail) {
            return head;
        }
        int val = head.val;
        ListNode slow = head.next;
        //用pre记录比pivot小的最后一个元素
        ListNode pre = head;
        ListNode fast;
        while (true) {
            //slow表示比pivot元素大的元素
            while (slow != tail && slow.val < val) {
                pre = slow;
                slow = slow.next;
            }
            if (slow == tail) {
                break;
            }
            //fast表示比pivot元素小的元素
            fast = slow.next;
            while (fast != tail && fast.val > val) {
                fast = fast.next;
            }
            if (fast == tail) {
                break;
            }
            //如果存在fast在slow之后,则交换两个元素的值
            swap(slow, fast);
            pre = slow;
            slow = slow.next;
        }
        //交换pivot和pre
        swap(head, pre);
        return pre;
    }

    private static void swap(ListNode one, ListNode two) {
        int tmp = one.val;
        one.val = two.val;
        two.val = tmp;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return val + ", ";
        }
    }

}

 

posted @ 2015-11-04 13:20  丶Blank  阅读(1350)  评论(0编辑  收藏  举报