Sorting Algorithms

Contents
  1. Bubble Sort
  2. Merge Sort

1. Bubble Sort

The Bubble Sort is a simple algorithm for ordering the values within an array. However, while it maybe simple, it is not as efficent as other algorithms unless the array it is being applies to meets specific conditions.

Here are the steps the algorithm takes:

  • Take the first two values in the array
    • Compare them (if value 1 is greater (>) than value 2)
    • If Value 1 is greater than value 2 - Swap them
    • Else If Value 1 is less than value 2 - Do nothing
  • Move into the next pair
  • Repeat until there are no more pairs to compare
  • Go back to the first two values in the array
  • Continue to repeat until you can go through the array without re-ordering any values

The number of passes required increase significantly with the number of items in the array. If the values are in reverse order (which is the worse case scenario) it would take n^2 comparisons. If you had 10 values in reverse order it would take 100 comparisons.


2. Merge Sort

A merge sort breaks down an array into smaller arrays and these smaller arrays are merged in pairs until it is rebuilt into order.

Firstly the array needs to be broken down into individual values. The values are then paired into arrays, and ordered correctly in these new arrays. These arrays are then paired and their values are placed into the correct order. This process is repeated until all the numbers are in order within one array.

Merge sort is more efficent than a bubble sort when used on larger arrays, however the process is not as simple as with a bubble sort.