6.4 Insertion Sort List

来源:互联网 发布:马拉车算法 编辑:程序博客网 时间:2024/06/03 04:19

原题链接:

I'm not familiar with insertion sorting of an array. To practice and get familiar with.

After checking the Data Structure book, here's the code:

public void insertionSort(int[] A){int i = 0;int j = 0lfor(i = 1; i < A.length; i++){int temp = A[i];j = i;//shift to rightwhile(j > 0 && A[j-1] >= temp){A[j] = A[j-1];j--;}//insertA[j] = temp;}}

To apply this algo directly to a sort list has a problem, i.e. we cannot track back a list (i.e. j -- in the above code). So how to deal with this problem?

The answer is that we do not need to track back. Instead, for each outer pointer, we compare all the nodes before it from the beginning. 

http://blog.csdn.net/linhuanmars/article/details/21144553

Time: O(n^2), Space: O(1)

public class Solution {    //code after reading answer from     public ListNode insertionSortList(ListNode head) {        ListNode dummy = new ListNode(0);        //note there is no "dummy.next = head", since this is done in the while loop        ListNode node = head;        //node is the outer pointer        while(node != null){            //first store the next node, since we may break the "next" links            ListNode next = node.next;            //always start comparing from the very beginning            //prev is the insertion point, after which we insert "node"            //If the nodes until "node" is ascending, increase the insertion pointer             ListNode prev = dummy;            while(prev.next != null && node.val > prev.next.val){                prev = prev.next;            }            //we find the insertion point (after prev)            node.next = prev.next;            prev.next = node;            node = next;        }        return dummy.next;    }}


0 0