### Sorting Algorithms

• Sorting

• Sorting:

 Sorting = re-arranging a collection of items in assending/descending order

• Sorting has been studied by computer scientists from very early on

• As a result:

 There are many different sort algorithms in existance

• Sample Sorting Algorithms

• We will study some easy sorting algorithms:

 Selection sort --- discussed in CS170 (simple to understand) Bubble sort --- very easy to implement (but slow) Insertion sort --- how people sort cards in their hand (homework)

• And also study some fast and more commonly used sorting algorithms:

 Merge sort === a fast sorting algorithm, one of the popular sort algorithm Quick sort === reasonably fast and pretty easy to implement

• Later, when we study binary trees, we will also learn about the:

 Heap sort agorithm (that is based on binary trees)

• Running time analysis

• Besides learning the sort algorithm, we will also compute their running time

• Dictactical note

• The common way provide sort functionality is through using the Comparable interface

Example:

• recall that we implemented the Selection Sort algorithm to sort any type of data

 ``` public class SelSort { public static void sort(Comparable[] a) { int i, j, min_j; // Array indices Comparable help; // helper variable for 3-way exchange /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i ++ ) { /* --------------------------------------------------- Find array element with min. value among a[i], a[i+1], ..., a[n-1] --------------------------------------------------- */ min_j = i; // Assume elem i (a[i]) is the minimum for ( j = i+1 ; j < a.length ; j++ ) { if ( a[j].compareTo(a[min_j]) < 0 ) { min_j = j; // We found a smaller minimum, update min_j } } /* --------------------------------------------------- Swap a[i] and a[min_j] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[min_j]; a[min_j] = help; } } } ```

• However, using Comparable objects will introduce an additional level of abstraction that can make understand the algorithm (that I am trying to teach) more difficult to understand

• So I will:

 Teach the algorithms using double input data (I.e.: the algorithm will sort an array of double Then I will show you the Comparable version of the algorithm