Category Archives: Sorting

Merge Sort

Merge sort is a sorting technique based on the divide and conquer technique. Recursively: split the list in half, sort each half, then merge the sorted halves together. Algorithm : MergeSort(A, p, r): if p > r return q = (p+r)/2 mergeSort(A, p, q) mergeSort(A, q+1, r) merge(A, p, q, r) Example : 30 64 26 46 109… Read More »

Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. It examines all pairs of adjacent elements, swapping them when they are out of order. Algorithm : for i in 0 .. n-2 for j in i .. n-1 if (a[j] > a[j+1]) swap(a[j], a[j+1]) We need… Read More »

Insertion Sort

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. For the 2nd, 3rd, 4th, etc. element: slide backwards into proper relative sorted position. This sort works on the principle of inserting an element at a particular position, hence the name Insertion Sort. Algorithm : for i in… Read More »

Selection Sort

In Selection Sort algorithm, First, find the smallest element and swap it with the first. Sort the rest of the list the same way. Algorithm : for i in 0 .. n-2 small := i for j in i+1 .. n-1 if (a[j] < a[small]) small := j swap(a[i], a[small]) Example : 30 64 26 46 109 21… Read More »