147. Insertion Sort List

Description

Sort a linked list using insertion sort.

Insertion Sort Definition

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.

147. Insertion Sort List_第1张图片
Insertion Sort

Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]

Example:

147. Insertion Sort List_第2张图片
insertion-sort

**Another Example: **
12, 11, 13, 5, 6

Let us loop for i = 1 (second element of the array) to 5 (Size of input array)

i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6

i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6

i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current position.
5, 11, 12, 13, 6

i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current position.
5, 6, 11, 12, 13
Code:

    /*Function to sort array using insertion sort*/
    void sort(int arr[])
    {
        int n = arr.length;
        for (int i=1; i=0 && arr[j] > key)
            {
                arr[j+1] = arr[j];
                j = j-1;
            }
            arr[j+1] = key;
        }
    }

Solution

Insertion Sort, time O(n^2), space O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null) {
            return null;
        }
        
        ListNode tail = head;
        
        while (tail.next != null) {
            if (tail.next.val < tail.val) {
                ListNode curr = tail.next;
                tail.next = curr.next;
                // insert curr between head and tail
                if (curr.val < head.val) {
                    curr.next = head;
                    head = curr;
                } else {
                    ListNode prev = head;
                    while (prev != tail && prev.next.val <= curr.val) {
                        prev = prev.next;
                    }
                    curr.next = prev.next;
                    prev.next = curr;
                }
            } else {
                tail = tail.next;
            }
        }
        
        return head;
    }
}

你可能感兴趣的:(147. Insertion Sort List)