3) Sorting Algorithms Lesson

Why Sort Data?

4 min to complete · By Jon Fincher

Imagine you are looking for someone in a telephone book -- you have their name and want to find their phone number or address. It should be fairly easy to do so, right? Since the telephone book is arranged in order, or sorted, by the names of the people and businesses, finding a particular person knowing their name should be fast and easy.

Now consider: what if, instead, you only had a phone number and wanted to find the name associated with it? This is a much more difficult task -- you now need to scan every page of the book and look at each phone number. Even if you had some code to help, this task would take some time. It would be great if you could rearrange the data or sort the data by phone number to make your search easier.

Sorting data is a basic technique in many computer applications. Most modern programming languages have a built-in sort function or method, so you may not need to build one yourself. However, it's good to know how they work and what the trade-offs are when using them.

First, though, you need to understand some basic concepts.

Sorting Concepts

Sorting data is the act of rearranging the data in a data structure so it's in some defined and known order. The order picked depends on the needs of the program and user -- you can sort text data alphabetically, dates from oldest to newest, numbers from high to low, or in reverse.

In order to sort data, you have to be able to compare one data value to another and determine which value is larger and which is smaller. Without this ability, there is no way to tell which data value should come first, which value should follow it, and so on. This property is often called being comparable or orderable, and it's key to all sorting algorithms.

In fact, Java provides an interface called Comparable for just this purpose -- any object that extends and implements this interface is sortable using the built-in Java sorting method. Python doesn't have interfaces, but objects can override and implement a set of dunder methods to provide comparisons between objects, which allows them to be sorted.

To make things easier to follow and understand, the examples in the following sections sort an array of numeric values, but the techniques are applicable to any collection of comparable objects. With that in mind, take a look at some popular sorting algorithms.

Summary: Sorting Data

You learned about several important concepts related to sorting data, including the need for the data to be comparable. You must be able to determine which data values are larger and which are smaller, by whatever criteria matters to you, to sort the data. You can make your own objects comparable by extending a Java interface or implementing a Python dunder method.