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

Programming Interviews: Exposed

Ace your Technical Interview Try Algorithms

In today's tight job market, competition for programming jobs is hotter than ever. This third edition of a popular guide to programming interviews includes new code examples, information on the latest languages, new chapters on sorting and design patterns, tips on using LinkedIn, and a downloadable app to help prepare applicants for the interview.

$ Check price
29.9929.99Amazon 4.5 logo(94+ reviews)

More Algorithms resources

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

Ad