Upload
alberta-booth
View
231
Download
0
Embed Size (px)
Citation preview
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, c are all integers3. a, b, c are three arrays of integers4. a, b are arrays of integers, c is an integer
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
Let’s work together
• Declare an array of 10 elements and initialize this array to even integers (starting from 0)
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.
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
Two-Dimensional Arrays• Two-dimensional arrays are useful in representing tabular
information.
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
Accessing an Element
• An element in a two-dimensional array is accessed by its row and column index.
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;
}
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];
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:
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 };.
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 };.
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
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
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
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.
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.
Searching Algorithms
• Examples of searching– Looking up a phone number– Accessing a Web site– Checking a word in the dictionary
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)
Search
• Example:
Number
402018 17 22 27 30
X= 40
0 1 2 3 4 5 6
Return: 3
Search
• Example:
Number
402018 17 22 27 30
X= 32
0 1 2 3 4 5 6
Return: NOT_FOUND (-1)
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.
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)
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}
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
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)
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
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.
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
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
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!!
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
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
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
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
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;
}
Binary Search Performance
• Successful Search– Best Case: 1 comparison
– Worst Case: log2N comparisons
• Unsuccessful Search– Best Case =
Worst Case: log2N comparisons
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.
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
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
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
“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
“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
“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
“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
“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
“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
“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)
“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)
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
=?
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
=?
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
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.
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
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
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
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
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
Example
Third pass
Number
17
0 1 2 3 4 5 6
2018 40 22 27 30
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
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
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
Example
Result
Number
17
0 1 2 3 4 5 6
2018 22 27 30 40
Code
public void selectionSort(int[] number) {int minIndex, size, temp;size = number.length;
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;
}}
Complexity analysis
Given an array with n elements, the total number of comparisons is approximately the square of the size of an array (N2)
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
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
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
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
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
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
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
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
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
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
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
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
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)