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;
 
  }
} 

Learn how data is stored

Data Structures and Algorithms in Java

Learn how data is stored Try Data Structures

Algorithms are the procedures that software programs use to manipulate data structures. Besides clear and simple example programs, the author includes a workshop as a small demonstration program executable on a Web browser. The programs demonstrate in graphical form what data structures look like and how they operate.

$ Check price
64.9964.99Amazon 4.5 logo(97+ reviews)

More Data Structures resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad