Sorting: re-arranging elements in an array into ascending order

• Introduction

• Information lookup is more efficient when the information is ordered in ascending (or descending) order.

Case in point: the words are ordered alphanumerically in a dictionary and looking for a word in a dictionary is easy. Just imagine if a dictionary contains all the words in an unordered manner - it would be impossible to find the definition of a word in such a dictionary !!!

• Arrays can be used to store data and searching for an item will be more efficient when the items in the array are ordered.

• We will study a simple computer algorithm called Bubble Sort to sort an array

This sorting algorithm is not in your text book... (I have no idea why...)

• Intro to Bubble Sort (with integers)

• Problem:

• You are given a set of integer numbers
• Put the integers in ascending order

• Example:

• Input: 65, 78, 25, 1
• Output: 1, 25, 65, 78

• Remember that the computer cannot consider all the numbers at once, but can only compare 2 different numbers at one time...

• The Bubble Sort algorithm compares EACH pairs of adjacent values and swap the values if they are out of order

• Example: execution of the Bubble Sort algorithm on input 65, 78, 25, 1

• Pair 1: 65, 78 - in correct order, do nothing
• Pair 2: 78, 25 - out of order, swap
• Pair 3: 78, 1 (you need to use to new order) - out of order, swap

Let's see what happens if we apply the procedure one more time:

• Pair 1: 65, 25 - out of order, swap
• Pair 2: 65, 1 - out of order, swap
• Pair 3: 65, 78 - in correct order, do nothing

It looks better, so let's see what happens if we apply the procedure one more time:

• Pair 1: 25, 1 - out of order, swap
• Pair 2: 25, 65 - in correct order, do nothing
• Pair 3: 65, 78 - in correct order, do nothing

It looks even better, so let's see what happens if we apply the procedure one more time:

• Pair 1: 1, 25 - in correct order, do nothing
• Pair 2: 25, 65 - in correct order, do nothing
• Pair 3: 65, 78 - in correct order, do nothing

Hey, the sequence of number is sorted !!!

Now, let's try to write the steps down - precisely...

• The Bubble Sort Algorithm (with integers)

• As indicated above, the Bubble Sort Algorithm does the following:

• Compare EACH pairs of adjacent values

• swap the values if they are out of order

• It is clear from the above example that the Bubble Sort Algorithm will eventually sort the values...

Clearly, if the list of value is NOT YET sorted , we should keep going.

But, if the list of value is sorted , we should STOP !

• The crucial question that we need to answer is:

When can we tell if a sequence of item is sorted (and we can stop)

The list of value is sorted if after comparing every pairs of adjacent values the algorithm DID NOT swap any pair of values (i.e., every pair is in the correct order )

• The Bubble Sort Algorithm can be written in psuedo code as follows:

 ``` int[] data = new int[...]; "fill data with value" boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for "every pair of values in data" { if ( "pair of value is out of order" ) { "swap the pair of values"; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Now we need to flesh out the psuedo steps...

• Here is how to handle the various psuedo codes:

• Handling "every pair of values in data"

The algorithm compares all these pairs of values:

• data[0] and data[1]
• data[1] and data[2]
• data[2] and data[3]
• ...
• data[data.length - 2] and data[data.length - 1]

We can use an index i running from 0 to data.length - 2:

```	for (i = 0; i <= data.length - 2; i++)
{
... compare data[i] and data[i+1] ...
}
```

The pair of values compared are: data[i] and data[i+1]

• Handling "pair of value is out of order"

Easy:

```        for (i = 0; i <= data.length - 2; i++)
{
if ( data[i]  > data[i+1] )
{

}
}
```

• Handling "swap the pair of values"

This is a classic and we have seen it before (three way exchange): (see: click here )

```
int help;

for (i = 0; i <= data.length - 2; i++)
{
if ( data[i]  > data[i+1] )
{
help = data[i];
data[i] = data[i+1];
data[i+1] = help;

done = false;   // Detect a swap - need to continue...
}
}
```

• Here is the Bubble Sort algorithm:

 ``` int[] data = new int[...]; int help; "fill data with value" /* ------------------------ Bubble Sort Algorithm ------------------------ */ boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for (i = 0; i <= data.length - 2; i++) { if ( data[i] > data[i+1] ) { help = data[i]; data[i] = data[i+1]; data[i+1] = help; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Example Program: (Bubble Sort on integers)

• Sorting Strings...

• The sorting algorithm does NOT change when you sort things other than integers, such as Strings.

• You do need to be aware that you may need to use different methods to tell you if a pair of item is out of order - for example, if you compare Strings, you need to use the compareTo() method

• Here is the Bubble Sort Algorithm from above re-written for Strings (I have only changed the type of data to String !):

 ``` String[] data = new String[...]; // Array of String (objects) "fill data with value" boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for "every pair of values in data" { if ( "pair of value is out of order" ) { "swap the pair of values"; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Here is how to handle the various psuedo codes for Item objects:

• Handling "every pair of values in data"

The algorithm compares all these pairs of values:

• data[0] and data[1]
• data[1] and data[2]
• data[2] and data[3]
• ...
• data[data.length - 2] and data[data.length - 1]

This step does not change when the type of the data is changed

We can use:

```	for (i = 0; i <= data.length - 2; i++)
{
... compare data[i] and data[i+1] ...
}
```

The pair of values compared are: data[i] and data[i+1]

• Handling "pair of value is out of order"

We need to express the fact that we want to compare the values on basis of they are Strings.

data[i].compareTo(data[i+1]) will compares Strings data[i] and data[i+1]
data[i].compareTo(data[i+1]) will returns a positive value when the strings are out of order.

```        for (i = 0; i <= data.length - 2; i++)
{
if ( data[i].compareTo(data[i+1]) > 0  )
{

}
}
```

• Handling "swap the pair of values"

This is a classic algorithm and we don't change a classic. But we do need the right type of help variable to make the exchange possible.

```
String help;

for (i = 0; i <= data.length - 2; i++)
{
if ( data[i]  > data[i+1] )
{
help = data[i];
data[i] = data[i+1];
data[i+1] = help;

done = false;   // Detect a swap - need to continue...
}
}
```

• Here is the Bubble Sort algorithm for Strings:

 ``` String[] data = new String[...]; String help; "fill data with value" /* ------------------------ Bubble Sort Algorithm ------------------------ */ boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for (i = 0; i <= data.length - 2; i++) { if ( data[i].compareTo(data[i+1]) > 0 ) { help = data[i]; data[i] = data[i+1]; data[i+1] = help; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Example Program: (Bubble Sort on Strings (= String objects))

• Sorting Data Items...

• Recall the structure of data item that we have used in our little persons database:

• Recall that the type of each entry is called Item

• The database is an array of Item objects

• We will write a program that sorts the items by ascending name

Information are often sorted for easy access...
Computers are ideally suited to do this mundane task...

• Here is the Bubble Sort Algorithm from above re-written for Items: (I have only changed the type of data to Item !):

 ``` Item[] data = new Item[...]; // Array of Item objects "fill data with value" boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for "every pair of values in data" { if ( "pair of value is out of order" ) { "swap the pair of values"; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Here is how to handle the various psuedo codes for Strings:

• Handling "every pair of values in data"

The algorithm compares all these pairs of values:

• data[0] and data[1]
• data[1] and data[2]
• data[2] and data[3]
• ...
• data[data.length - 2] and data[data.length - 1]

This step does not change when the type of the data is changed

We can use:

```	for (i = 0; i <= data.length - 2; i++)
{
... compare data[i] and data[i+1] ...
}
```

The pair of values compared are: data[i] and data[i+1]

• Handling "pair of value is out of order"

We need to express the fact that we want to compare the Items on basis of the name fields - which is a String.

data[i].getName() will return the name in data[i]
data[i+1].getName() will return the name in data[i+1]

data[i].getName().compareTo(data[i+1].getName()) compares the names in data[i] and data[i+1]

```        for (i = 0; i <= data.length - 2; i++)
{
if ( data[i].getName().compareTo(data[i+1].getName()) > 0  )
{

}
}
```

• Handling "swap the pair of values"

This is a classic algorithm and we don't change a classic. But we do need the right type of help variable to make the exchange possible.

```
Item help;

for (i = 0; i <= data.length - 2; i++)
{
if ( data[i]  > data[i+1] )
{
help = data[i];
data[i] = data[i+1];
data[i+1] = help;

done = false;   // Detect a swap - need to continue...
}
}
```

• Here is the Bubble Sort algorithm for Items sorted based on the "name" field:

 ``` Item[] data = new Item[...]; Item help; "fill data with value" /* ------------------------ Bubble Sort Algorithm ------------------------ */ boolean done; // The variable will tell us if we need to continue done = false; while ( ! done ) { done = true; // Set to true to detect if some pair is swapped for (i = 0; i <= data.length - 2; i++) { if ( data[i].getName().compareTo(data[i+1].getName()) > 0 ) { help = data[i]; data[i] = data[i+1]; data[i+1] = help; done = false; // Detect a swap - need to continue... } } // NOTE: done will be "true" if all pair were in correct order ! } ```

• Example Program: (Bubble Sort on Item objects)