81
Array Search & Sort (continues)

Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Embed Size (px)

Citation preview

Page 1: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Array Search & Sort (continues)

Page 2: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly questions

• Array declaration:int[] a, b, c;

1. a is an array of integers, b and c are two integers

2. a, b, c are all integers3. a, b, c are three arrays of integers4. a, b are arrays of integers, c is an integer

Page 3: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly questions

• Array declaration:int[] a, b, c;

1. a is an array of integers, b and c are two integers

2. a, b, c are all integers3. a, b, c are three arrays of integers4. a, b are arrays of integers, c is an integer

Page 4: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Let’s work together

• Declare an array of 10 elements and initialize this array to even integers (starting from 0)

Page 5: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Good practice

• Constant variables also are called named constants or read-only variables. Such variables often make programs more readable than programs that use literal values (e.g., 10)—a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used.

Page 6: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

What happen if:

• Assigning a value to a constant after the variable has been initialized

Compilation error

• Attempting to use a constant before it is initalized

Compilation error

Page 7: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Two-Dimensional Arrays• Two-dimensional arrays are useful in representing tabular

information.

Page 8: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Declaring and Creating a 2-D ArrayDeclaration

<data type> [][] <variable>; //variation 1<data type> <variable>[][]; //variation 2

Creation

<variable> = new <data type> [ <size1> ][ <size2> ]

double[][] payScaleTable;

payScaleTable

= new double[4][5];

3

2

1

0

43210payScaleTable

Page 9: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Accessing an Element

• An element in a two-dimensional array is accessed by its row and column index.

Page 10: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sample 2-D Array Processing

double[ ] average = { 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];

}

average[i] = average[i] / payScaleTable[i].length;

}

Page 11: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Java Implementation of 2-D Arrays

•The sample array creationpayScaleTable = new double[4][5];

is really a shorthand for–payScaleTable = new double [4][ ];

payScaleTable[0] = new double [5];payScaleTable[1] = new double [5];payScaleTable[2] = new double [5];payScaleTable[3] = new double [5];

Page 12: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Two-Dimensional Arrays• Subarrays may be different lengths. • Executing

triangularArray = new double[4][ ];for (int i = 0; i < 4; i++)triangularArray[i] = new double [i + 1];

results in an array that looks like:

Page 13: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly review

Which statement below initializes array items to contain 3 rows and 2 columns?

a. int items[][] = { { 2, 4 }, { 6, 8 }, { 10, 12 } };.

b. int items[][] = { { 2, 6, 10 }, { 4, 8, 12 } };.

c. int items[][] = { 2, 4 }, { 6, 8 }, { 10, 12 };.

d. int items[][] = { 2, 6, 10 }, { 4, 8, 12 };.

Page 14: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly review

Which statement below initializes array items to contain 3 rows and 2 columns?

a. int items[][] = { { 2, 4 }, { 6, 8 }, { 10, 12 } };.

b. int items[][] = { { 2, 6, 10 }, { 4, 8, 12 } };.

c. int items[][] = { 2, 4 }, { 6, 8 }, { 10, 12 };.

d. int items[][] = { 2, 6, 10 }, { 4, 8, 12 };.

Page 15: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

1 // Fig. 7.17: InitArray.java

2 // Initializing two-dimensional arrays.

3

4 public class InitArray

5 {

6 // create and output two-dimensional arrays

7 public static void main( String args[] )

8 {

9 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };

10 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };

11

12 System.out.println( "Values in array1 by row are" );

13 outputArray( array1 ); // displays array1 by row

14

15 System.out.println( "\nValues in array2 by row are" );

16 outputArray( array2 ); // displays array2 by row

17 } // end main

18

Use nested array initializers to

initialize array1

Use nested array initializers of different lengths to

initialize array2

Page 16: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example19 // output rows and columns of a two -dimensional array

20 public static void outputArray( int array[][] )

21 {

22 // loop through array's rows

23 for ( int row = 0; row < array.length; ro w++ )

24 {

25 // loop through columns of current ro w

26 for ( int column = 0; column < array[ row ].length; column++ )

27 System.out.printf( "%d " , array[ row ][ column ] );

28

29 System.out.println(); // start new line of output

30 } // end outer for

31 } // end method outputArray

32 } // end class InitArray Values in array1 by row are 1 2 3 4 5 6 Values in array2 by row are 1 2 3 4 5 6

Page 17: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Searching and Sorting

• Searching– Determining whether a search key is present

in data

• Sorting– Places data in order based on one or more

sort keys

Page 18: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly question

Which of the following is a way to sort data?

a.Alphabetically.b. In increasing numerical order.c. Based on an account number.d. All of the above.

Page 19: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

On the fly question

Which of the following is a way to sort data?

a.Alphabetically.b. In increasing numerical order.c. Based on an account number.d. All of the above.

Page 20: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Searching Algorithms

• Examples of searching– Looking up a phone number– Accessing a Web site– Checking a word in the dictionary

Page 21: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Searching

• Problem definition:Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).

(Assumptions: no duplicate entries in the array)

Page 22: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Search

• Example:

Number

402018 17 22 27 30

X= 40

0 1 2 3 4 5 6

Return: 3

Page 23: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Search

• Example:

Number

402018 17 22 27 30

X= 32

0 1 2 3 4 5 6

Return: NOT_FOUND (-1)

Page 24: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Searching

• We will count the number of comparisons the algorithms make to analyze their performance.– The ideal searching algorithm will make the

least possible number of comparisons to locate the desired data.

– Two separate performance analyses are normally done:

• one for successful search and • another for unsuccessful search.

Page 25: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Searching

• We will count the number of comparisons the algorithms make to analyze their performance.– The ideal searching algorithm will make the

least possible number of comparisons to locate the desired data.

– Two separate performance analyses are normally done:• one for successful search (x is found) and • another for unsuccessful search (x is not

found)

Page 26: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Linear Search• Search the array from the first to the last position in linear

progression.

public int linearSearch ( int[] number, int searchValue ) {

}

int pos = 0;while (pos < number.length && number[pos] != searchValue) {

pos++;}

if (pos == number.length) { //Not foundreturn NOT_FOUND;

} else { return pos; //Found, return the position}

Page 27: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Linear Search Performance

• We analyze the successful and unsuccessful searches separately.

• Successful Search– Best Case: 1 comparison– Worst Case: N comparisons (N – array size)

• Unsuccessful Search– Best Case = Worst Case: N comparisons

Page 28: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Binary Search

• If the array is sorted, then we can apply the binary search technique.

• Sorted array: all the values in the array are arranged in ascending or descending ordera[i] >= a[j] (i>= j)

ORa[i] <= a[j] (i>= j)

Page 29: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

• Unsorted array

• Sorted array

Number

402018 17 22 27 30

0 1 2 3 4 5 6

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Page 30: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Binary Search

• The basic idea is straightforward: First search the value in the middle position. If X is less than this value, then search the middle of the left half next. If X is greater than this value, then search the middle of the right half next. Continue in this manner.

Page 31: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Successful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 44 )low high mid

0 8#1

highlow

2

highlow

mid

38 < 44 low = mid+1 = 5

mid

4

Page 32: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Successful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 44 )low high mid

0 8#1

2

highlow

mid

44 < 77high = mid-1=5

4

mid

6

highlow

5 8#2

Page 33: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Successful Search - 3

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 44 )low high mid

0 8#1

2

highlow

mid

44 == 44

45 8#2 6

highlow

5 5#3

mid

5

Successful Search!!

Page 34: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Unsuccessful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 45 )low high mid

0 8#1

highlow

2

highlow

mid

38 < 45 low = mid+1 = 5

mid

4

Page 35: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Unsuccessful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 45 )low high mid

0 8#1

2

highlow

mid

45 < 77high = mid-1=5

4

mid

6

highlow

5 8#2

Page 36: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Unsuccessful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 45 )low high mid

0 8#1

2

highlow

mid

44 < 45

45 8#2 6

highlow

5 5#3

mid

5

low = mid+1 = 6

Page 37: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sequence of Unsuccessful Search

5 12 17 23 38 44 77

0 1 2 3 4 5 6 7 8

84 90

search( 45 )low high mid

0 8#1

2

highlow

mid

45 8#2 65 5#3 5

high low

6 5#4

Unsuccessful Search

low > highno more elements to search

Page 38: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Binary Search Routinepublic int binarySearch (int[] number, int searchValue) {

int low = 0;int high = number.length – 1; int mid = (low + high) / 2;

while (low <= high && number[mid] != searchValue) {if (number[mid] < searchValue) {

low = mid + 1;} else {

high = mid - 1;}mid = (low + high) / 2;

}

if (low > high) {mid = NOT_FOUND;

}return mid;

}

Page 39: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Binary Search Performance

• Successful Search– Best Case: 1 comparison

– Worst Case: log2N comparisons

• Unsuccessful Search– Best Case =

Worst Case: log2N comparisons

Page 40: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Binary Search Performance

• Since the portion of an array to search is cut into half after every comparison, we compute how many times the array can be divided into halves.

• After K comparisons, there will be N/2K elements in the list. We solve for K when N/2K = 1, deriving K = log2N.

Page 41: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Comparing N and log2N PerformanceArray Size Linear – N Binary –

log2N10 10 450 50 6100 100 7500 500 91000 1000 102000 2000 113000 3000 124000 4000 125000 5000 136000 6000 137000 7000 138000 8000 139000 9000 1410000 10000 14

Page 42: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Project 2 discussion

Customer name 1 2 3 4 TotalHien Nguyen 32.96 0 0 0 32.96…….Tom Hanks 0 199.99 0 200.10 400.09

Page 43: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Project 2 - pseudocode

1. Read a line from invoice.dat 2. Make an Invoice object from that line 3. Declare an array of String that has maximum 100 elements

(nameArray) 4. Declare a 2D array, rows= 100, columns: 4 or 5

(invoiceArray) 5. Check if the customer name exists in the nameArray. If it

doesn’t, add to the nameArray. If it does exist there, you need to find the index of this name in the nameArray. ( use some kinds of search: linearsearch will work fine here)

6. If the customer name exists (i), update the invoiceArray based on the price and the code of warehouse

7. If the customer name does not exist, but you already add it in step 5 (say new index for this name is j), add one element to invoiceArray at index j based on the price and code of warehouse

Page 44: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time” review

1. Suppose an array (SORTED) contains 1024 elements. What are the least and the greatest number of comparisons for a successful search using binary search?a. 1 and 10b. 1 and 9c. 1 and 8d. 1 and 1024

Page 45: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time” review

1. Suppose an array (SORTED) contains 1024 elements. What are the least and the greatest number of comparisons for a successful search using binary search?a. 1 and 10b. 1 and 9c. 1 and 8d. 1 and 1024

Page 46: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

2. How many comparisons do we need to find x=6 using linear search on the following sorted array A (10 elements): -8 -6 -4 -2 0 2 4 6 8 10a. 6b. 7c. 8d. 9

Page 47: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

2. How many comparisons do we need to find x=6 using linear search on the following sorted array A (10 elements): -8 -6 -4 -2 0 2 4 6 8 10a. 6b. 7c. 8d. 9

Page 48: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

3. How many comparisons do we need to find x=6 using binary search on the following sorted array A (10 elements): -8 -6 -4 -2 0 2 4 6 8 10a. 1b. 2c. 3d. 4

Page 49: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

3. How many comparisons do we need to find x=6 using binary search on the following sorted array A (10 elements): -8 -6 -4 -2 0 2 4 6 8 10a. 1b. 2c. 3d. 4

Page 50: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

4. Which of the following is NOT true?a. Linear search requires no special constraint

on the arrayb. Binary search requires the array to be sortedc. Binary search and linear search have the

same best case performance (successful search)

d. Binary search and linear search have the same worst case performance (successful search)

Page 51: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

“Just in time review”

4. Which of the following is NOT true?a. Linear search requires no special constraint

on the arrayb. Binary search requires the array to be sortedc. Binary search and linear search have the

same best case performance (successful search)

d. Binary search and linear search have the same worst case performance (successful search)

Page 52: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

X = 40?

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Middle position = (6+0)/2 = 3Comparing: 40 and number[3](22) => Not match

=?

Page 53: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

X = 40?

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Middle position = (6+4)/2 = 5Comparing: 40 and number[5](30) => Not match

=?

Page 54: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

X = 40?

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Middle position = (6+6)/2 = 6Comparing: 40 and number[6](40) => matchReturn 6

Page 55: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Sorting

• The problem statement:Given an array of N integer values, arrange the values into ascending order.

• We will count the number of comparisons the algorithms make to analyze their performance. – The ideal sorting algorithm will make the least possible

number of comparisons to arrange data in a designated order.

• We will compare different sorting algorithms by analyzing their worst-case performance.

Page 56: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

• Input:

• Output

Number

402018 17 22 27 30

0 1 2 3 4 5 6

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Page 57: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Selection Sort

• Step1 : Find the smallest integer in the array• Step 2: Exchange the element in the first

position and the smallest element. Now the smallest element is in the first position. Cross out the number found in step 1 from consideration.

• Step 3: Repeat steps 1 and 2 until all numbers in the array are sorted

Page 58: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Input (unsorted):

Input

number

402018 17 22 27 30

0 1 2 3 4 5 6

Number

0 1 2 3 4 5 6

Page 59: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

First passNumber

402018 17 22 27 30

0 1 2 3 4 5 6

Number

17

0 1 2 3 4 5 6

1820 40 22 27 30

Page 60: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Second passNumber

17

0 1 2 3 4 5 6

1820 40 22 27 30

Number

17

0 1 2 3 4 5 6

2018 40 22 27 30

Page 61: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Third pass

Number

17

0 1 2 3 4 5 6

2018 40 22 27 30

Page 62: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Fourth pass

Number

17

0 1 2 3 4 5 6

2018 40 22 27 30

Number

17

0 1 2 3 4 5 6

2018 22 40 27 30

Page 63: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Fifth pass

Number

17

0 1 2 3 4 5 6

2018 22 40 27 30

Number

17

0 1 2 3 4 5 6

2018 22 27 40 30

Page 64: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Sixth pass

Number

17

0 1 2 3 4 5 6

2018 22 27 40 30

Number

17

0 1 2 3 4 5 6

2018 22 27 30 40

Page 65: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Example

Result

Number

17

0 1 2 3 4 5 6

2018 22 27 30 40

Page 66: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Code

public void selectionSort(int[] number) {int minIndex, size, temp;size = number.length;

Page 67: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Code

for (int i=0; i<size-2; i++) {minIndex = i;for (int j=i+1; j<size-1; j++) {

if (number[j] < number[minIndex])

minIndex=j;}temp= number[i];number[i]=number[minIndex];number[minIndex] = temp;

}}

Page 68: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Complexity analysis

Given an array with n elements, the total number of comparisons is approximately the square of the size of an array (N2)

Page 69: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

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

Page 70: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

1 // Figure 16.10: MergeSort.java

2 // Class that creates an array filled with random integers.

3 // Provides a method to sort the array with merge sort.

4 import java.util.Random;

5

6 public class MergeSort

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 MergeSort( 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 data[ i ] = 10 + generator.nextInt( 90 );

19 } // end MergeSort constructor

20

21 // calls recursive split method to begin merge sorting

22 public void sort()

23 {

24 sortArray( 0, data.length - 1 ); // split entire array

25 } // end method sort 26

Call recursive helper method

Page 71: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

27 // splits array, sorts subarrays and merges subarrays into sorted array

28 private void sortArray( int low, int high )

29 {

30 // test base case; size of array equals 1

31 if ( ( high - low ) >= 1 ) // if not base case

32 {

33 int middle1 = ( low + high ) / 2; // calculate middle of array

34 int middle2 = middle1 + 1; // calculate next element over

35

36 // output split step

37 System.out.println( "split: " + subarray( low, high ) );

38 System.out.println( " " + subarray( low, middle1 );

39 System.out.println( " " + subarray( middle2, high ) );

40 System.out.println();

41

42 // split array in half; sort each half (recursive calls)

43 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 merge ( low, middle1, middle2, high );

48 } // end if

49 } // end method split 50

Page 72: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

51 // merge two sorted subarrays into one sorted subarray

52 private void merge( int left, int middle1, int middle2, int right )

53 {

54 int leftIndex = left; // index into left subarray

55 int rightIndex = middle2; // index into right subarray

56 int combinedIndex = left; // index into temporary working array

57 int[] combined = new int[ data.length ]; // working array

58

59 // output two subarrays before merging

60 System.out.println( "merge: " + subarray( left, middle1 ) );

61 System.out.println( " " + subarray( middle2, right ) );

62

63 // merge arrays until reaching end of either

64 while ( leftIndex <= middle1 && rightIndex <= right )

65 {

66 // place smaller of two current elements into result

67 // and move to next space in arrays

68 if ( data[ leftIndex ] <= data[ rightIndex ] )

69 combined[ combinedIndex++ ] = data[ leftIndex++ ];

70 else

71 combined[ combinedIndex++ ] = data[ rightIndex++ ];

72 } // end while 73

Page 73: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

74 // if left array is empty

75 if ( leftIndex == middle2 )

76 // copy in rest of right array

77 while ( rightIndex <= right )

78 combined[ combinedIndex++ ] = data[ rightIndex++ ];

79 else // right array is empty

80 // copy in rest of left array

81 while ( leftIndex <= middle1 )

82 combined[ combinedIndex++ ] = data[ leftIndex++ ];

83

84 // copy values back into original array

85 for ( int i = left; i <= right; i++ )

86 data[ i ] = combined[ i ];

87

88 // output merged array

89 System.out.println( " " + subarray( left, right ) );

90 System.out.println();

91 } // end method merge 92

Page 74: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

93 // method to output certain values in array

94 public String subarray( int low, int high )

95 {

96 StringBuffer temporary = new StringBuffer();

97

98 // output spaces for alignment

99 for ( int i = 0; i < low; i++ )

100 temporary.append( " " );

101

102 // output elements left in array

103 for ( int i = low; i <= high; i++ )

104 temporary.append( " " + data[ i ] );

105

106 return temporary.toString();

107 } // end method subarray

108

109 // method to output values in array

110 public String toString()

111 {

112 return subarray( 0, data.length - 1 );

113 } // end method toString

114 } // end class MergeSort

Page 75: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

1 // Figure 16.11: MergeSortTest.java

2 // Test the merge sort class.

3

4 public class MergeSortTest

5 {

6 public static void main( String[] args )

7 {

8 // create object to perform merge sort

9 MergeSort sortArray = new MergeSort( 10 );

10

11 // print unsorted array

12 System.out.println( "Unsorted:" + sortArray + "\n" );

13

14 sortArray.sort(); // sort array

15

16 // print sorted array

17 System.out.println( "Sorted: " + sortArray );

18 } // end main

19 } // end class MergeSortTest

Page 76: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

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

Page 77: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

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

Page 78: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

merge: 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

Page 79: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Merge Sort

• Start=0, end = 6, mid=(6+0)/2 = 3

Number

402018 17 22 27 30

0 1 2 3 4 5 6

2018 4017 22 27 30

Page 80: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

Merge Sort. Start=0, end = 3, mid=(3+0)/2 = 1

. Start=4, end =6, mid=(4+6)/2=5

2018

22 27 30

4017

Page 81: Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,

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)