插入排序:每一趟将一個待排序的記錄,按照其關鍵字的大小插入到有序隊列的合适位置裡,知道全部插入完成。
在講解直接插入排序之前,先讓我們腦補一下我們打牌的過程。
先拿一張5在手裡,
再摸到一張4,比5小,插到5前面,
摸到一張6,嗯,比5大,插到5後面,
摸到一張8,比6大,插到6後面,
以上的過程,其實就是典型的直接插入排序,每次将一個新資料插入到有序隊列中的合适位置裡。
public
class
Solution {
public
ListNode insertionSortList(ListNode head) {
if
(head ==
null
){
return
null
;
}
ListNode curNode = head.next;
ListNode pNode =
new
ListNode(
);
pNode.next = head;
head.next =
null
;
while
(curNode !=
null
){
ListNode compareNode = pNode;
while
(compareNode !=
null
){
if
(compareNode.next ==
null
|| compareNode.next.val>= curNode.val){
break
;
}
compareNode = compareNode.next;
}
ListNode temp = curNode.next;
curNode.next = compareNode.next;
compareNode.next = curNode;
curNode = temp;
}
return
pNode.next;
}
}