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
- 6.4 Insertion Sort List
- 6.4—排序—Insertion Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- Leetcode: Insertion Sort List
- [LeeCode] Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.SimpleTriggerBea
- Android万能分辨率适应法
- poj1458_Common Subsequence
- 不吃青春饭,关于程序员将来的发展方向
- H264 获取SPS与PPS(附源码)
- 6.4 Insertion Sort List
- 菜单资源
- guava&&java
- codeforces Div.2 B.Suffix Structures
- 提问
- windows系统相关系统命令
- Illegal modifier for parameter ***; only final is permitted
- Oracle修改带数据的字段类型
- 天气预报接口