(148)-(Sort List )-(用nlogn实现排序,可以用快排,归并和堆排序)-(我对于分治始终不能很好地掌握)
其中归并的最坏时间复杂度为N平方
//用nlogn实现排序
//归并排序和快速排序都可以实现这个要求,
//首先归并做一次吧。嗯
//典型的分治思想
//【2】internalMergeSort(int []a ,int left,int right) 反复调用 internalMergeSort internalMergeSort 和MergeSortedArray(a,b,left,middle,right)
//【3】MergeSortedArray(int []a,int left,int middle,int right) //left和middle+1控制下界,middle和right控制上界 都是操作a的,结果保存在temp中
public class Solution
{
public ListNode sortList(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null)
{
fast = fast.next.next;
if (fast == null)
{
break;
}
slow = slow.next;
}
//利用快慢指针直接找到链表的中点
ListNode right = slow.next;
//这里意味着通过slow对head进行截断右边的操作
slow.next = null;
//截断后的head,此时仅仅表示左边,
//对左边进行处理
ListNode left = sortList(head);
//对右边进行处理
right = sortList(right);
return mergeTwoLists(left, right);
}
public ListNode mergeTwoLists(ListNode fir_head, ListNode sec_head)
{
if (fir_head == null)
{
return sec_head;
}
if (sec_head == null)
{
return fir_head;
}
ListNode final_ans = new ListNode(0);
ListNode r_ans=final_ans;
while (fir_head != null && sec_head != null)
{
if (fir_head.val <= sec_head.val)
{
r_ans.next =fir_head;
r_ans=r_ans.next;
fir_head=fir_head.next;
}
else
{
r_ans.next=sec_head;
r_ans=r_ans.next;
sec_head=sec_head.next;
}
}
if (fir_head != null)
{
r_ans.next =fir_head;
r_ans=r_ans.next;
fir_head=fir_head.next;
}
if (sec_head != null)
{
r_ans.next=sec_head;
r_ans=r_ans.next;
sec_head=sec_head.next;
}
return final_ans.next;
}
}