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

Bubble Sort

PreviousSortingNextMerge Sort

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 bs(arr: Vector[Int]): Vector[Int] = {

  @tailrec
  def go(arr: Vector[Int], i: Int, swaps: Boolean): (Vector[Int], Boolean) = {
    if (i == arr.length) arr -> swaps
    else {
      if (arr(i - 1) > arr(i)) {
         go(arr.updated(i, arr(i - 1)).updated(i - 1, arr(i)), i + 1, true
      } else
        go(arr, i + 1, swaps)
    }
  }

  val (res, swaps) = go(arr, 1, false)
  if (!swaps) res
  else bs(res)
}