Sorting Algorithms

Sorting Algorithms

·

4 min read

This is the first real post that may contain any value, well at least to noobs like me, and of course this post will likely be under construction for a few years or decades.

Anyways, this article is about algorithms that we can use to sort data.

I believe the best way for us to learn about this subject is to visually understand how each algorithm does the sorting per each iteration of the loop.


Contents


What are some Sorting Algorithms?

  • QuickSort
  • BubbleSort
  • InsertionSort
  • SelectionSort

This is just a small list -- there are far too many algorithms to memorize, but we should understand some simple ones. In my opinion, just make sure to know QuickSort, BubbleSort, and other sorting algorithms for different data structures.

For a complete guide to sorting algorithms, click here


by the way... the listed code is in Java

SelectionSort

public static void SelectionSort(int[] array)
{
    for (int i = 0; i < array.length; i++)
    {
          for (int j = i+1; j < array.length; j++)
          {
                if (array[j] < array[i])
                {
                      int temp = array[j];
                      array[j] = array[i];
                      array[i] = temp;
                }
          }
    }
}

It is important to understand that a SelectionSort is not an efficient sorting algorithm, but is a very visually clear algorithm.

Let's explain what happens in a Selection Sort.

  1. We loop through the array, indexing the first element, array[i], AND the element after the first element, array[j]
  2. If the element (array[j]) in front of our first element (array[i]) is a LESSER value, then we need to SWAP these values
  3. We declare a temporary variable to hold the value of array[j] because we want to assign array[j] the value of array[i] while assigning array[i] the value of array[j]
  4. Swap the values

InsertionSort

public static void insertionSort(int[] nums)
    {
        for (int i = 1; i < nums.length; i++)
        {
            int copy = nums[i];
            int j = i;
            while (j > 0 && nums[j-1] > copy)
            {
                nums[j] = nums[j-1];
                j--;
            }
            nums[j] = copy;
        }
    }

BubbleSort

public static void bubbleSort(int[] nums)
    {
        for (int i = 0; i < nums.length - 1; i++)
        {
            boolean swapMade = false;
            for (int j = 0; j < nums.length - 1 - i; j++)
            {
                if (nums[j] > nums[j+1])
                {
                    swapMade = true;
                    int temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
            if (!swapMade)
            {
                break;
            }
        }
    }