Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
1
16
Searching and
Sorting
1992-2007 Pearson Education, Inc. All rights reserved.
2
With sobs and tears he sorted out
Those of the largest size ...
— Lewis Carroll
Attempt the end, and never stand to doubt;
Nothing’s so hard, but search will find it out.
— Robert Herrick
‘Tis in my memory lock’d,
And you yourself shall keep the key of it.
— William Shakespeare
It is an immutable law in business that words are
words, explanations are explanations, promises are
promises — but only performance is reality.
— Harold S. Green
1992-2007 Pearson Education Inc. All rights reserved.
3
OBJECTIVES
In this chapter you will learn:
To search for a given value in an array using
linear search and binary search.
To sort arrays using the iterative selection and
insertion sort algorithms.
To sort arrays using the recursive merge sort
algorithm.
To determine the efficiency of searching and
sorting algorithms.
To use loop invariants to help ensure the
correctness of your programs.
1992-2007 Pearson Education, Inc. All rights reserved.
4
16.1
Introduction
16.2
Searching Algorithms
16.2.1 Linear Search
16.2.2 Binary Search
16.3
Sorting Algorithms
16.3.1 Selection Sort
16.3.2 Insertion Sort
16.3.3 Merge Sort
16.4
Invariants
16.5
Wrap-up
1992-2007 Pearson Education, Inc. All rights reserved.
5
16.1 Introduction
• Searching
– Determining whether a search key is present in data
• Sorting
– Places data in order based on one or more sort keys
1992-2007 Pearson Education, Inc. All rights reserved.
6
Chapter
Algorithm
Location
Searching Algorithms:
16
17
19
Linear Search
Binary Search
Recursive Linear Search
Recursive Binary Search
Linear search of a List
Binary tree search
binarySearch method of class
Collections
Section 16.2.1
Section 16.2.2
Exercise 16.8
Exercise 16.9
Exercise 17.21
Exercise 17.23
Fig. 19.14
Sorting Algorithms:
16
17
19
Selection Sort
Insertion Sort
Recursive Merge Sort
Bubble Sort
Bucket Sort
Recursive Quicksort
Binary tree sort
Section 16.3.1
Section 16.3.2
Section 16.3.3
Exercises 16.3 and 16.4
Exercise 16.7
Exercise 16.10
Section 17.9
sort method of class Collections Fig. 19.8–Fig. 19.11
SortedSet collection
Fig. 19.19
Fig. 16.1 | Searching and sorting algorithms in this text.
1992-2007 Pearson Education, Inc. All rights reserved.
7
16.2 Searching Algorithms
• Examples of searching
– Looking up a phone number
– Accessing a Web site
– Checking a word in the dictionary
1992-2007 Pearson Education, Inc. All rights reserved.
8
16.2.1 Linear Search
• Linear search
– Searches each element sequentially
– If search key is not present
• Tests each element
• When algorithm reaches end of array, informs user search
key is not present
– If search key is present
• Test each element until it finds a match
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.2: LinearArray.java
2
// Class that contains an array of random integers and a method
3
4
// that will search that array sequentially
import java.util.Random;
9
5
6
7
8
9
public class LinearArray
{
private int[] data; // array of values
private static Random generator = new Random();
10
11
12
// create array of given size and fill with random numbers
public LinearArray( int size )
13
14
{
data = new int[ size ]; // create space for array
15
16
17
18
19
20
// fill array with random ints in range 10-99
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
} // end LinearArray constructor
1992-2007 Pearson Education, Inc. All rights reserved.
21
// perform a linear search on the data
22
public int linearSearch( int searchKey )
23
24
25
{
26
27
28
29
Iterate through array
// loop through array sequentially
for ( int index = 0; index < data.length; index++ )
if ( data[ index ] == searchKey )
return index; // return index of integer
Test each element sequentially
return -1; // integer was not found
} // end method linearSearch
30
31
32
// method to output values in array
33
34
public String toString()
{
35
StringBuffer temporary = new StringBuffer();
36
37
38
// iterate through array
for ( int element : data )
39
40
41
42
10
Return index containing search key
temporary.append( element + " " );
temporary.append( "\n" ); // add endline character
return temporary.toString();
43
} // end method toString
44 } // end class LinearArray
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
3
// Fig 16.3: LinearSearchTest.java
// Sequentially search an array for an item.
import java.util.Scanner;
4
5
6
7
public class LinearSearchTest
{
public static void main( String args[] )
8
9
10
11
{
// create Scanner object to input data
Scanner input = new Scanner( System.in );
11
12
13
14
int searchInt; // search key
int position; // location of search key in array
15
// create array and output it
16
17
LinearArray searchArray = new LinearArray( 10 );
System.out.println( searchArray ); // print array
18
19
// get input from user
20
System.out.print(
21
22
"Please enter an integer value (-1 to quit): " );
searchInt = input.nextInt(); // read first int from user
23
24
25
26
// repeatedly input an integer; -1 terminates the program
while ( searchInt != -1 )
{
27
28
29
// perform linear search
position = searchArray.linearSearch( searchInt );
1992-2007 Pearson Education, Inc. All rights reserved.
30
31
32
33
34
35
if ( position == -1 ) // integer was not found
12
System.out.println( "The integer " + searchInt +
" was not found.\n" );
else // integer was found
System.out.println( "The integer " + searchInt +
" was found in position " + position + ".\n" );
36
37
// get input from user
38
System.out.print(
39
"Please enter an integer value (-1 to quit): " );
40
searchInt = input.nextInt(); // read next int from user
41
42
} // end while
} // end main
43 } // end class LinearSearchTest
16 35 68 10 48 36 81 60 84 21
Please enter an integer value (-1 to quit): 48
The integer 48 was found in position 4.
Please enter an integer value (-1 to quit): 60
The integer 60 was found in position 7.
Please enter an integer value (-1 to quit): 33
The integer 33 was not found.
Please enter an integer value (-1 to quit): -1
1992-2007 Pearson Education, Inc. All rights reserved.
13
Efficiency of Linear Search
• Big O Notation
– Indicates the worst-case run time for an algorithm
– In other words, how hard an algorithm has to work to
solve a problem
– Constant run time
• O(1)
• Does not grow as the size of the array increases
– Linear run time
• O(n)
• Grows proportional to the size of the array
1992-2007 Pearson Education, Inc. All rights reserved.
14
Efficiency of Linear Search
• Big O Notation
– Constant run time
• O(1)
• Does not grow as the size of the array increases
– Linear run time
• O(n)
• Grows proportional to the size of the array
– Quadratic run time
• O(n2)
• Grows proportional to the square of the size of the array
1992-2007 Pearson Education, Inc. All rights reserved.
15
Efficiency of Linear Search
• Linear search algorithm
– O(n)
– Worst case: algorithm checks every element before being
able to determine if the search key is not present
– Grows proportional to the size of the array
1992-2007 Pearson Education, Inc. All rights reserved.
16
Performance Tip 16.1
Sometimes the simplest algorithms perform
poorly. Their virtue is that they are easy to
program, test and debug. Sometimes more
complex algorithms are required to realize
maximum performance.
1992-2007 Pearson Education, Inc. All rights reserved.
17
16.2.2 Binary Search
• Binary search
– More efficient than linear search
– Requires elements to be sorted
– Tests the middle element in an array
• If it is the search key, algorithm returns
• Otherwise, if the search key is smaller, eliminates larger half
of array
• If the search key is larger, eliminates smaller half of array
– Each iteration eliminates half of the remaining elements
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.4: BinaryArray.java
2
// Class that contains an array of random integers and a method
3
// that uses binary search to find an integer.
4
import java.util.Random;
5
import java.util.Arrays;
18
6
7
public class BinaryArray
8
{
9
private int[] data; // array of values
10
private static Random generator = new Random();
11
12
// create array of given size and fill with random integers
13
public BinaryArray( int size )
14
{
15
data = new int[ size ]; // create space for array
16
17
// fill array with random ints in range 10-99
18
for ( int i = 0; i < size; i++ )
19
data[ i ] = 10 + generator.nextInt( 90 );
20
21
22
23
Arrays.sort( data );
} // end BinaryArray constructor
1992-2007 Pearson Education, Inc. All rights reserved.
24
25
26
// perform a binary search on the data
public int binarySearch( int searchElement )
{
Store high, low and middle of
remaining array to search
27
28
int low = 0; // low end of the search area
int high = data.length - 1; // high end of the search area
29
30
31
32
int middle = ( low + high + 1 ) / 2; // middle element
int location = -1; // return value; -1 if not found Loop
33
{
19
until key is found or no
elements left to search
do // loop to search for element
34
35
// print remaining elements of array
System.out.print( remainingElements( low, high ) );
36
37
38
39
40
// output spaces for alignment
for ( int i = 0; i < middle; i++ )
If search
System.out.print( "
" );
System.out.println( " * " ); // indicate current middle
41
42
43
// if the element is found at the middle
if ( searchElement == data[ middle ] )
element is the middle
element
Return middle element
If search
location = middle; // location is the current middle
element is less than
middle element
44
45
46
// middle element is too high
47
else if ( searchElement < data[ middle ] )
48
49
50
51
high = middle - 1; // eliminate the higher half
else // middle element is too low
low = middle + 1; // eliminate the lower half
Eliminate higher half
Else, eliminate lower half
1992-2007 Pearson Education, Inc. All rights reserved.
52
53
middle = ( low + high + 1 ) / 2; // recalculate the middle
} while ( ( low <= high ) && ( location == -1 ) );
Update middle of array
54
55
56
57
return location; // return location of search key
} // end method binarySearch
58
59
60
61
// method to output certain values in array
public String remainingElements( int low, int high )
{
StringBuffer temporary = new StringBuffer();
Return location of element
62
63
// output spaces for alignment
64
65
for ( int i = 0; i < low; i++ )
temporary.append( "
" );
66
67
// output elements left in array
68
69
for ( int i = low; i <= high; i++ )
temporary.append( data[ i ] + " " );
70
71
temporary.append( "\n" );
72
return temporary.toString();
73
20
} // end method remainingElements
74
75
// method to output values in array
76
77
public String toString()
{
78
return remainingElements( 0, data.length - 1 );
79
} // end method toString
80 } // end class BinaryArray
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.5: BinarySearchTest.java
2
// Use binary search to locate an item in an array.
3
import java.util.Scanner;
21
4
5
public class BinarySearchTest
6
{
7
public static void main( String args[] )
8
{
9
// create Scanner object to input data
10
Scanner input = new Scanner( System.in );
11
12
int searchInt; // search key
13
int position; // location of search key in array
14
15
// create array and output it
16
BinaryArray searchArray = new BinaryArray( 15 );
17
System.out.println( searchArray );
18
1992-2007 Pearson Education, Inc. All rights reserved.
19
// get input from user
20
21
System.out.print(
"Please enter an integer value (-1 to quit): " );
22
23
searchInt = input.nextInt(); // read an int from user
System.out.println();
24
25
26
// repeatedly input an integer; -1 terminates the program
while ( searchInt != -1 )
27
28
29
22
{
// use binary search to try to find integer
position = searchArray.binarySearch( searchInt );
30
31
32
33
34
35
36
// return value of -1 indicates integer was not found
if ( position == -1 )
System.out.println( "The integer " + searchInt +
" was not found.\n" );
else
System.out.println( "The integer " + searchInt +
" was found in position " + position + ".\n" );
37
38
39
// get input from user
40
41
System.out.print(
"Please enter an integer value (-1 to quit): " );
42
searchInt = input.nextInt(); // read an int from user
43
44
System.out.println();
} // end while
45
} // end main
46 } // end class BinarySearchTest
1992-2007 Pearson Education, Inc. All rights reserved.
13 23 24 34 35 36 38 42 47 51 68 74 75 85 97
23
Please enter an integer value (-1 to quit): 23
13 23 24 34 35 36 38 42 47 51 68 74 75 85 97
*
13 23 24 34 35 36 38
*
13 23 24
*
The integer 23 was found in position 1.
Please enter an integer value (-1 to quit): 75
13 23 24 34 35 36 38 42 47 51 68 74 75 85 97
*
47 51 68 74 75 85 97
*
75 85 97
*
75
*
The integer 75 was found in position 12.
Please enter an integer value (-1 to quit): 52
13 23 24 34 35 36 38 42 47 51 68 74 75 85 97
*
47 51 68 74 75 85 97
*
47 51 68
*
68
*
The integer 52 was not found.
Please enter an integer value (-1 to quit): -1
1992-2007 Pearson Education, Inc. All rights reserved.
24
Efficiency of Binary Search
• Binary search
– Each comparison halves the size of the remaining array
– Results in O(log n)
– Called logarithmic run time
1992-2007 Pearson Education, Inc. All rights reserved.
25
16.3 Sorting Algorithms
• Sorting data
– Placing data into some particular order
• A bank sorts checks by account number
• Telephone companies sort accounts by name
– End result is always the same – a sorted array
– Choice of algorithm affects how you achieve the result and,
most importantly, how fast you achieve the result
1992-2007 Pearson Education, Inc. All rights reserved.
26
16.3.1 Selection Sort
• Selection sort
– Simple, but inefficient sorting algorithm
– First iteration selects smallest element in array and swaps
it with the first element
– Each iteration selects the smallest remaining unsorted
element and swaps it with the next element at the front of
the array
– After i iterations, the smallest i elements will be sorted in
the first i elements of the array
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
// Fig 16.6: SelectionSort.java
// Class that creates an array filled with random integers.
3
4
// Provides a method to sort the array with selection sort.
import java.util.Random;
27
5
6
7
8
9
public class SelectionSort
{
private int[] data; // array of values
private static Random generator = new Random();
10
11
// create array of given size and fill with random integers
12
13
public SelectionSort( int size )
{
14
data = new int[ size ]; // create space for array
15
16
// fill array with random ints in range 10-99
17
18
19
20
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
} // end SelectionSort constructor
21
// sort array using selection sort
22
23
public void sort()
{
24
int smallest; // index of smallest element
25
26
// loop over data.length - 1 elements
27
28
29
30
Variable to store index of smallest
element
Loop length – 1 times
for ( int i = 0; i < data.length - 1; i++ )
{
smallest = i; // first index of remaining array
1992-2007 Pearson Education, Inc. All rights reserved.
31
// loop to find index of smallest element
32
33
for ( int index = i + 1; index < data.length; index++ )
if ( data[ index ] < data[ smallest ] )
smallest = index;
28
Loop over remaining elements
34
35
36
37
38
39
swap( i, smallest ); // swap smallest element into
position
Locate
smallest
printPass( i + 1, smallest ); // output pass of algorithm
} // end outer for
} // end method sort
40
41
42
43
// helper method to swap values in two elements
public void swap( int first, int second )
{
Swap smallest element with first
unsorted element
int temporary = data[ first ]; // store first in temporary
data[ first ] = data[ second ]; // replace first with second
data[ second ] = temporary; // put temporary in second
44
45
46
47
48
49
50
} // end method swap
51
52
{
53
54
55
56
57
58
59
remaining element
// print a pass of the algorithm
public void printPass( int pass, int index )
System.out.print( String.format( "after pass %2d: ", pass ) );
// output elements till selected item
for ( int i = 0; i < index; i++ )
System.out.print( data[ i ] + " " );
System.out.print( data[ index ] + "* " ); // indicate swap
1992-2007 Pearson Education, Inc. All rights reserved.
60
// finish outputting array
61
for ( int i = index + 1; i < data.length; i++ )
62
System.out.print( data[ i ] + "
29
" );
63
64
System.out.print( "\n
" ); // for alignment
65
66
67
// indicate amount of array that is sorted
for ( int j = 0; j < pass; j++ )
68
69
System.out.print( "-- " );
System.out.println( "\n" ); // add endline
70
71
72
73
74
} // end method indicateSelection
// method to output values in array
public String toString()
{
75
76
StringBuffer temporary = new StringBuffer();
77
78
79
// iterate through array
for ( int element : data )
temporary.append( element + "
80
81
temporary.append( "\n" ); // add endline character
82
83
" );
return temporary.toString();
} // end method toString
84 } // end class SelectionSort
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.7: SelectionSortTest.java
2
// Test the selection sort class.
30
3
4
5
public class SelectionSortTest
{
6
public static void main( String[] args )
7
{
8
// create object to perform selection sort
9
SelectionSort sortArray = new SelectionSort( 10 );
10
11
12
System.out.println( "Unsorted array:" );
System.out.println( sortArray ); // print unsorted array
13
14
sortArray.sort(); // sort array
15
16
System.out.println( "Sorted array:" );
17
System.out.println( sortArray ); // print sorted array
18
} // end main
19 } // end class SelectionSortTest
1992-2007 Pearson Education, Inc. All rights reserved.
Unsorted array:
61 87 80 58 40
31
50
20
13
71
45
after pass
1: 13
--
87
80
58
40
50
20
after pass
2: 13
--
20
--
80
58
40
50
87* 61
71
45
after pass
3: 13
--
20
--
40
--
58
80* 50
87
61
71
45
after pass
4: 13
--
20
--
40
--
45
--
80
50
87
61
71
58*
after pass
5: 13
--
20
--
40
--
45
--
50
--
80* 87
61
71
58
after pass
6: 13
--
20
--
40
--
45
--
50
--
58
--
87
61
71
80*
after pass
7: 13
--
20
--
40
--
45
--
50
--
58
--
61
--
87* 71
after pass
8: 13
--
20
--
40
--
45
--
50
--
58
--
61
--
71
--
87* 80
after pass
9: 13
--
20
--
40
--
45
--
50
--
58
--
61
--
71
--
80
--
Sorted array:
13 20 40 45
50
58
61
71
80
61* 71
45
80
87*
87
1992-2007 Pearson Education, Inc. All rights reserved.
32
Efficiency of Selection Sort
• Selection sort
– Outer for loop iterates over n – 1 elements
– Inner for loop iterates over remaining elements in the
array
– Results in O(n2)
1992-2007 Pearson Education, Inc. All rights reserved.
33
16.3.2 Insertion Sort
• Insertion sort
– Another simple, but inefficient sorting algorithm
– First pass takes the second element and inserts it into the
correct order with the first element
– Each iteration takes the next element in the array and
inserts it into the sorted elements at the beginning of the
array
– After i iterations, the first i elements of the array are in
sorted order
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.8: InsertionSort.java
2
// Class that creates an array filled with random integers.
3
// Provides a method to sort the array with insertion sort.
4
import java.util.Random;
34
5
6
public class InsertionSort
7
{
8
private int[] data; // array of values
9
private static Random generator = new Random();
10
11
// create array of given size and fill with random integers
12
public InsertionSort( int size )
13
{
14
data = new int[ size ]; // create space for array
15
16
// fill array with random ints in range 10-99
17
for ( int i = 0; i < size; i++ )
18
19
data[ i ] = 10 + generator.nextInt( 90 );
} // end InsertionSort constructor
20
1992-2007 Pearson Education, Inc. All rights reserved.
21
// sort array using insertion sort
22
public void sort()
23
{
24
Declare variable to store element to
be inserted
35
int insert; // temporary variable to hold element to insert
Iterate over length – 1 elements
25
26
// loop over data.length - 1 elements
27
for ( int next = 1; next < data.length; next++ )
28
{
29
// store value in current element
30
insert = data[ next ];
31
32
// initialize location to place element
33
int moveItem = next;
Store value to insert
Search for location to place inserted
element
34
35
// search for place to put current element
36
while ( moveItem > 0 && data[ moveItem - 1 ] > insert
Move) one
37
{
38
// shift element right one slot
39
data[ moveItem ] = data[ moveItem - 1 ];
40
moveItem--;
41
} // end while
element to the right
Decrement location to insert
element
42
43
data[ moveItem ] = insert; // place inserted element
44
printPass( next, moveItem ); // output pass of algorithm
45
46
} // end for
} // end method sort
Insert element into sorted place
47
1992-2007 Pearson Education, Inc. All rights reserved.
48
// print a pass of the algorithm
49
public void printPass( int pass, int index )
50
{
51
36
System.out.print( String.format( "after pass %2d: ", pass ) );
52
53
// output elements till swapped item
54
for ( int i = 0; i < index; i++ )
55
System.out.print( data[ i ] + "
" );
56
57
System.out.print( data[ index ] + "* " ); // indicate swap
58
59
// finish outputting array
60
for ( int i = index + 1; i < data.length; i++ )
61
System.out.print( data[ i ] + "
" );
62
63
System.out.print( "\n
" ); // for alignment
64
65
// indicate amount of array that is sorted
66
for( int i = 0; i <= pass; i++ )
67
68
69
System.out.print( "--
" );
System.out.println( "\n" ); // add endline
} // end method printPass
70
1992-2007 Pearson Education, Inc. All rights reserved.
71
// method to output values in array
72
public String toString()
73
{
74
37
StringBuffer temporary = new StringBuffer();
75
76
// iterate through array
77
for ( int element : data )
78
temporary.append( element + "
" );
79
80
temporary.append( "\n" ); // add endline character
81
return temporary.toString();
82
} // end method toString
83 } // end class InsertionSort
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Fig 16.9: InsertionSortTest.java
2
// Test the insertion sort class.
38
3
4
5
public class InsertionSortTest
{
6
public static void main( String[] args )
7
{
8
// create object to perform selection sort
9
InsertionSort sortArray = new InsertionSort( 10 );
10
11
12
System.out.println( "Unsorted array:" );
System.out.println( sortArray ); // print unsorted array
13
14
sortArray.sort(); // sort array
15
16
System.out.println( "Sorted array:" );
17
System.out.println( sortArray ); // print sorted array
18
} // end main
19 } // end class InsertionSortTest
1992-2007 Pearson Education, Inc. All rights reserved.
Unsorted array:
40 17 45 82 62
39
32
30
44
93
10
after pass
1: 17* 40
-- --
45
82
62
32
30
44
93
10
after pass
2: 17
--
40
--
45* 82
--
62
32
30
44
93
10
after pass
3: 17
--
40
--
45
--
82* 62
--
32
30
44
93
10
after pass
4: 17
--
40
--
45
--
62* 82
-- --
32
30
44
93
10
after pass
5: 17
--
32* 40
-- --
45
--
62
--
82
--
30
44
93
10
after pass
6: 17
--
30* 32
-- --
40
--
45
--
62
--
82
--
44
93
10
after pass
7: 17
--
30
--
32
--
40
--
44* 45
-- --
62
--
82
--
93
10
after pass
8: 17
--
30
--
32
--
40
--
44
--
45
--
62
--
82
--
93* 10
--
after pass
9: 10* 17
-- --
30
--
32
--
40
--
44
--
45
--
62
--
82
--
Sorted array:
10 17 30 32
40
44
45
62
82
93
--
93
1992-2007 Pearson Education, Inc. All rights reserved.
40
Efficiency of Insertion Sort
• Insertion sort
– Outer for loop iterates over n – 1 elements
– Inner while loop iterates over preceding elements of array
– Results in O(n2)
1992-2007 Pearson Education, Inc. All rights reserved.
41
16.3.3 Merge Sort
• Merge sort
– More efficient sorting algorithm, but also more complex
– Splits array into two approximately equal sized subarrays,
sorts each subarray, then merges the subarrays
– The following implementation is recursive
• Base case is a one-element array which cannot be unsorted
• Recursion step splits an array into two pieces, sorts each
piece, then merges the sorted pieces
1992-2007 Pearson Education, Inc. All rights reserved.
1
2
// Figure 16.10: MergeSort.java
// Class that creates an array filled with random integers.
3
4
// Provides a method to sort the array with merge sort.
import java.util.Random;
5
6
public class MergeSort
7
8
9
10
11
12
13
14
15
16
17
18
42
{
private int[] data; // array of values
private static Random generator = new Random();
// create array of given size and fill with random integers
public MergeSort( int size )
{
data = new int[ size ]; // create space for array
// fill array with random ints in range 10-99
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
19
20
21
22
23
} // end MergeSort constructor
24
25
26
sortArray( 0, data.length - 1 ); // split entire array
} // end method sort
// calls recursive split method to begin merge sorting
public void sort()
{
Call recursive helper method
1992-2007 Pearson Education, Inc. All rights reserved.
27
28
// splits array, sorts subarrays and merges subarrays into sorted array
private void sortArray( int low, int high )
Test for base
29
30
31
{
32
// test base case; size of array equals 1
if ( ( high - low ) >= 1 ) // if not base case
43
case
Compute middle of array
{
33
34
35
int middle1 = ( low + high ) / 2; // calculate middle of array
int middle2 = middle1 + 1; // calculate next element over
36
// output split step
37
System.out.println( "split:
" + subarray( low, high ) );
38
39
40
System.out.println( "
System.out.println( "
System.out.println();
" + subarray( low, middle1 );
" + subarray( middle2, high ) );
Compute element one spot to right
of middle
Recursively sort first half of array
41
42
43
// split array in half; sort each half (recursive calls)
Recursively
sortArray( low, middle1 ); // first half of array
44
sortArray( middle2, high ); // second half of array
45
46
// merge two sorted arrays after split calls return
47
48
49
50
merge ( low, middle1, middle2, high );
} // end if
} // end method split
sort second half of
array
Merge the two sorted subarrays
1992-2007 Pearson Education, Inc. All rights reserved.
51
// merge two sorted subarrays into one sorted subarray
52
53
54
private void merge( int left, int middle1, int middle2, int right )
Index of element
{
int leftIndex = left; // index into left subarray
44
in left array
Index of element in right array
55
int rightIndex = middle2; // index into right subarray
56
57
58
int combinedIndex = left; // index into temporary working array
Index
to place element
int[] combined = new int[ data.length ]; // working
array
59
60
// output two subarrays before merging
System.out.println( "merge:
" + subarray( left, middle1
Array )to);
hold
61
System.out.println( "
62
63
// merge arrays until reaching end of either
64
while ( leftIndex <= middle1 && rightIndex <= right )
65
{
array
sorted elements
" + subarray( middle2, right ) );
Loop until reach end of either array
Determine smaller of two elements
66
67
// place smaller of two current elements into result
// and move to next space in arrays
68
if ( data[ leftIndex ] <= data[ rightIndex ] )
69
70
combined[ combinedIndex++ ] = data[ leftIndex++ ];
else
71
72
73
in combined
combined[ combinedIndex++ ] = data[ rightIndex++ ];
} // end while
Place smaller element in combined
array
1992-2007 Pearson Education, Inc. All rights reserved.
74
75
// if left array is empty
if ( leftIndex == middle2 )
If left array is empty
76
// copy in rest of right array
77
78
while ( rightIndex <= right )
combined[ combinedIndex++ ] = data[ rightIndex++ ];
79
80
81
82
// copy in rest of left array
while ( leftIndex <= middle1 )
85
for ( int i = left; i <= right; i++ )
data[ i ] = combined[ i ];
87
89
90
91
92
Fill with elements of left array
combined[ combinedIndex++ ] = data[ leftIndex++ ];
// copy values back into original array
88
Fill with elements of right array
If right array is empty
else // right array is empty
83
84
86
45
// output merged array
System.out.println( "
System.out.println();
} // end method merge
Copy values back to original array
" + subarray( left, right ) );
1992-2007 Pearson Education, Inc. All rights reserved.
93
// method to output certain values in array
94
public String subarray( int low, int high )
95
96
{
46
StringBuffer temporary = new StringBuffer();
97
98
// output spaces for alignment
99
100
for ( int i = 0; i < low; i++ )
temporary.append( "
" );
101
// output elements left in array
for ( int i = low; i <= high; i++ )
102
103
104
105
106
107
temporary.append( " " + data[ i ] );
return temporary.toString();
} // end method subarray
108
109
110
// method to output values in array
public String toString()
111
112
{
113
} // end method toString
return subarray( 0, data.length - 1 );
114 } // end class MergeSort
1992-2007 Pearson Education, Inc. All rights reserved.
1
// Figure 16.11: MergeSortTest.java
2
// Test the merge sort class.
47
3
4
5
public class MergeSortTest
{
6
public static void main( String[] args )
7
{
8
// create object to perform merge sort
9
MergeSort sortArray = new MergeSort( 10 );
10
11
12
// print unsorted array
System.out.println( "Unsorted:" + sortArray + "\n" );
13
14
sortArray.sort(); // sort array
15
16
// print sorted array
17
System.out.println( "Sorted:
18
" + sortArray );
} // end main
19 } // end class MergeSortTest
1992-2007 Pearson Education, Inc. All rights reserved.
Unsorted: 75 56 85 90 49 26 12 48 40 47
split:
75 56 85 90 49 26 12 48 40 47
75 56 85 90 49
26 12 48 40 47
split:
75 56 85 90 49
75 56 85
90 49
split:
75 56 85
75 56
85
split:
75 56
75
56
48
1992-2007 Pearson Education, Inc. All rights reserved.
49
merge:
75
56
56 75
merge:
56 75
85
56 75 85
split:
90 49
90
49
merge:
90
49
49 90
merge:
56 75 85
49 90
49 56 75 85 90
split:
26 12 48 40 47
26 12 48
40 47
split:
26 12 48
26 12
48
split:
26 12
26
12
1992-2007 Pearson Education, Inc. All rights reserved.
merge:
50
26
12
12 26
merge:
12 26
48
12 26 48
split:
40 47
40
47
merge:
40
47
40 47
merge:
12 26 48
40 47
12 26 40 47 48
merge:
49 56 75 85 90
12 26 40 47 48 49 56 75 85 90
Sorted:
12 26 40 47 48 49 56 75 85 90
1992-2007 Pearson Education, Inc. All rights reserved.
51
Efficiency of Merge Sort
• Merge sort
– Far more efficient that selection sort or insertion sort
– Last merge requires n – 1 comparisons to merge entire
array
– Each lower level has twice as many calls to method merge,
with each call operating on an array half the size which
results in O(n) total comparisons
– There will be O(log n) levels
– Results in O(n log n)
1992-2007 Pearson Education, Inc. All rights reserved.
52
Algorithm
Location
Big O
Linear Search
Binary Search
Recursive Linear Search
Recursive Binary Search
Sorting Algorithms:
Section 16.2.1
Section 16.2.2
Exercise 16.8
Exercise 16.9
O(n)
O(log n)
O(n)
O(log n)
Selection Sort
Insertion Sort
Merge Sort
Bubble Sort
Section 16.3.1
Section 16.3.2
Section 16.3.3
Exercises 16.3 and 16.4
O(n2)
O(n2)
O(n log n)
O(n2)
Searching Algorithms:
Fig. 16.12 | Searching and sorting algorithms with Big O values.
1992-2007 Pearson Education, Inc. All rights reserved.
53
n=
O(log n)
O(n)
O(n log n)
O(n2)
1
2
3
4
5
10
100
1,000
1,000,000
1,000,000,000
0
1
1
1
1
1
2
3
6
9
1
2
3
4
5
10
100
1000
1000000
1000000000
0
2
3
4
5
10
200
3000
6000000
9000000000
1
4
9
16
25
100
10000
106
1012
1018
Fig. 16.13 | Number of comparisons for common Big O notations.
1992-2007 Pearson Education, Inc. All rights reserved.
54
16.4 Invariants
• Invariant
– Is an assertion that is true before and after a portion of
your code executes
– Most common type is a loop invariant
1992-2007 Pearson Education, Inc. All rights reserved.
55
16.4 Invariants
• Loop invariant remains true:
– Before the execution of the loop
– After every iteration of the loop body
– When the loop terminates
1992-2007 Pearson Education, Inc. All rights reserved.
56
16.4 Invariants
• Four steps to developing a loop from a loop
invariant
– Set initial values for any loop control variables
– Determine the condition that causes the loop to terminate
– Modify the control variable so the loop progresses toward
termination
– Check that the invariant remains true at the end of each
iteration
1992-2007 Pearson Education, Inc. All rights reserved.