Functional Programming
  • Preface
  • Getting Started
  • Sorting
    • Bubble Sort
    • Merge Sort
    • Insertion Sort
  • Stacks
    • Stack
  • Queues
    • Queue
    • Binary Heap (Priority Queue)
  • Trees
    • Binary Tree (Unbalanced)
    • Prefix Trie
  • Graphs
    • Undirected
    • Directed
    • Edge Weighted
  • Dynamic Programming
    • Knapsack
    • Longest Common Substring
    • Staircase
  • Leetcode/InterviewBit
    • 2 Sum [Easy]
    • Longest Valid Parentheses [Medium-Hard]
    • Kth Smallest Element [Medium]
    • Max Profit [2 variations: 1st Easy 2nd Hard]
    • Pretty Print 2D Matrix [Easy]
    • Max Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
    • Permutations [Medium]
    • Next Permutation [Medium]
Powered by GitBook
On this page
  • Algorithm
  • Implementation

Was this helpful?

  1. Sorting

Insertion Sort

PreviousMerge SortNextStacks

Last updated 6 years ago

Was this helpful?

Algorithm

Space (if swaps done in place): O(1)O(1)O(1)

Complexity: O(n2)O(n^2)O(n2)

Implementation

def is(arr: Vector[Int]): Vector[Int] = {

  @tailrec
  def backwards(arr: Vector[Int], i: Int): Vector[Int] =
    if (i == 0) arr
    else if (arr(i - 1) > arr(i))
      backwards(arr.updated(i, arr(i - 1)).updated(i - 1, arr(i)), i - 1)
    else arr

  @tailrec
  def forwards(i: Int, arr: Vector[Int]): Vector[Int] =
    if (i == arr.length) arr
    else forwards(i + 1, backwards(arr, i))

  forwards(1, arr)
}