Sorting Algorithms In Brief

This article is a brief description of some set of widely used sorting techniques and it's implementations in golang.

Summary:

  1. Insertion Sort
  2. Selection Sort

Insertion Sort

This algorithm maintains a sorted portion and unsorted portion, in the given list of elements to be sorted.

It picks a corner element from unsorted portion and inserts it into correct location in the sorted portion.

Here is the golang implementation of insertion sort.

Run in Go Playground

Here the algorithm sorts the elements in ascending order.

The outer for loop, scan the array from start to end. ( with itr iterator.)

The left portion pointed by outer for loop iterator will be the sorted portion.

On every iteration of outer for loop, inner for loop shift the element pointed by outer iterator to its correct locations.

This has been achieved by continuous comparison (arr[inItr] < arr[inItr-1]) and swapping.


Selection Sort

Similar to insertion sort, selection sort also maintains a sorted and unsorted portion in the given list.

Selection sort picks smallest element among unsorted portion and grows sorted portion on iteratively.

Run in Go Playground

The outer loop tracks the sorted portion and inner loop finds index of smallest element from the unsorted portion.

Comments

Popular posts from this blog

Theory of Computation | Symbols, Alphabets, Strings and Language

Operating Systems | Types and Functions

Computer Network | Flow control Methods: Stop and Wait