java实现单链表的快速排序

新建一个单链表

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

快速排序的思想,首先找到一个基准元素,然后把大于该元素的,小于该元素的分别放到两边,再递归下去。这是一个n*logn级别的算法。

public class LinkNodeFsatSort {
    public static Node paration(Node begin,Node end){
        if(begin == null||begin == end){
            return begin;
        }
        int cur = begin.value;//先以第一个元素为基准
        Node index = begin;//index指向最后一个小于基准的元素
        Node der = begin.next;//der指向当前进行比较的元素
        while(der!=end){
            if(der.value<cur){
                index = index.next;
                int tem = der.value;
                der.value = index.value;
                index.value = tem;
            }//如比较元素小于基准,交换
            der = der.next;//比较下一个元素
        }
        begin.value = index.value;
        index.value = cur;//把基准元素和最后一个小于基准的元素交换,此时基准两边都分好
        
        return index;
    }
    
    public static void FastSort(Node begin,Node end){
        if(begin == null||begin == end){
            return;//如果链表为空或只有一项,我们直接返回即可
        }
        Node index = paration(begin,end);
        FastSort(begin,index);
        FastSort(index,end);
    }
}
View Code

 

posted on 2018-03-19 10:32  himikoo  阅读(348)  评论(0编辑  收藏  举报

导航