DEV Community

Cover image for Insertion sort
Pavel Ro
Pavel Ro

Posted on

3 3

Insertion sort

The best analogy for insertion sort is a deck of cards. And you need to put them in the right order from smallest to greatest. You hold at least one card constant while you move the other cards around it to sort everything into order. The element that you considering could be moved one spot or over multiple spots.

def insertion_sort(array)
  return array if array.size <= 1

  (array.length).times do |i|
    while i > 0
      if array[i-1] > array[i]
        array[i], array[i-1] = array[i-1], array[i]
      else
        break
      end
      i-=1
    end
  end
  array
end
Enter fullscreen mode Exit fullscreen mode
  • return array if it's empty or include one element
  • iterate through array with (array.length).times, i represents the index of the array
  • in the loops when element's index > 0
  • we set if/else condition and if previous value larger than current we swap them, else we terminate loops
  • if loops does not terminate we decrease index of array and continue

Time Complexity: О(n^2)
Space Complexity: О(n)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay