01. Introduction to Sorting

In this section, we'll cover sorting. Before we get started, let's cover the base class and some sorting basics.

Stable vs. Unstable

A sort that is stable means that order of elements with the same key are preserved.

For example, if I had a list of {f, F, D, d, W, n, K, i} and I wanted to sort alphabetically (ignoring the cases) I would have {D, d, f, F, i, n, K}. Since D and d, along with f and F have the same value in terms of precedence, the letter that appears before the other in the original list appears first in the sorted array.

Sort class

All the lessons in the section will use code that inherits from the Sort class. We could use generics to sort different types of objects (with respective .equals()) methods, but we'll keep it simple and focus on the algorithmic parts.

/**
 * Contains the functionalities of any class that is able to Sort an array of ints.
 * @author Code Snipcademy
 * @version 1.0.0 May 16, 2015.
 */
public class Sort {
 
  /**
   * Swap two elements in our int array.
   * @param index1 First index
   * @param index2 Second index
   */
  public static void swap(int[] inputArray, int index1, int index2) {
 
    int temp;
 
    temp = inputArray[index1];
    inputArray[index1] = inputArray[index2];
    inputArray[index2] = temp;
 
  }
} 

Ace your Technical Interview

Cracking the Coding Interview

Ace your Technical Interview Try Algorithms

Cracking the Coding Interview will tell you exactly what you need to know to land your dream job at Google, Amazon, Microsoft or any other big tech companies. Packed with over 189 interview questions and detailed solutions, this book will help you train for the classic white-board technical interview. A must have for any CS major.

$ Check price
39.9539.95Amazon 4.5 logo(266+ reviews)

More Algorithms resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Ad