LeetCode in Swift: Insertion Sort List

Problem Statement

Sort a linked list using insertion sort.

Original LeetCode problem page

My Solution in Swift

Every time after inserting a list node, I use a variable to record the reference to that node. When next uninserted list node comes in, it checks from the recorded last inserted node instead of restarting the checking from the head list node. Only if the new list node is smaller than the previous list node of the last inserted list node, the inserting process needs to restart from the very beginning. In this way, the insertion sort algorithm is O(n) in best case and O(n2) in both average and worst case. The space complexity is O(1).

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Insertion Sort List26.869ms Save  (1657) Save  (1645)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift