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 integers 3. a, b, c are three arrays of integers 4. 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 integers 3. a, b, c are three arrays of integers 4. 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 Array Declaration [][] ; //variation 1 [][]; //variation 2 Creation = new [ ][ ] double[][] payScaleTable; payScaleTable = new double[4][5]; payScaleTable
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 creation payScaleTable = 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 Use nested array initializers to initialize array1 Use nested array initializers of different lengths to initialize array2
Example 19 // 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; row++ ) 24 { 25 // loop through columns of current row 26 for (int column =0; column < array[ row ].length; column++ ) 27 System.out.printf("%d ", array[ row ][ column ] ); 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 Values in array2 by row are
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 X= Return: 3
Search Example: Number X= 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 found return 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 order a[i] >= a[j] (i>= j) OR a[i] = j)
Example Unsorted array Sorted array Number Number
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 search( 44 ) lowhighmid 0808 #1 high low 38 < 44 low = mid+1 = 5 mid 4
Sequence of Successful Search search( 44 ) lowhighmid 0808 #1 44 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2
Sequence of Successful Search search( 44 ) lowhighmid 0808 #1 44 == #2 6 highlow5 #3 mid 5 Successful Search!!
Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 high low 38 < 45 low = mid+1 = 5 mid 4
Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 45 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2
Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 #1 44 < #2 6 highlow5 #3 mid 5 low = mid+1 = 6
Sequence of Unsuccessful Search search( 45 ) lowhighmid 0808 # #2 65 #3 5 highlow 6565 #4 Unsuccessful Search low > high no more elements to search
Binary Search Routine public 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: log 2 N comparisons Unsuccessful Search –Best Case = Worst Case: log 2 N 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/2 K elements in the list. We solve for K when N/2 K = 1, deriving K = log 2 N.
Comparing N and log 2 N Performance Array SizeLinear – NBinary – log 2 N
Project 2 discussion Customer name12 34 Total Hien Nguyen ……. Tom Hanks
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 10 b. 1 and 9 c. 1 and 8 d. 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 10 b. 1 and 9 c. 1 and 8 d. 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): a. 6 b. 7 c. 8 d. 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): a. 6 b. 7 c. 8 d. 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): a. 1 b. 2 c. 3 d. 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): a. 1 b. 2 c. 3 d. 4
“Just in time review” 4. Which of the following is NOT true? a.Linear search requires no special constraint on the array b.Binary search requires the array to be sorted c.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 array b.Binary search requires the array to be sorted c.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 Middle position = (6+0)/2 = 3 Comparing: 40 and number[3](22) => Not match =?
Example X = 40? Number Middle position = (6+4)/2 = 5 Comparing: 40 and number[5](30) => Not match =?
Example X = 40? Number Middle position = (6+6)/2 = 6 Comparing: 40 and number[6](40) => match Return 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 Number
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 Number
Example First pass Number Number
Example Second pass Number Number
Example Third pass Number
Example Fourth pass Number Number
Example Fifth pass Number Number
Example Sixth pass Number Number
Example Result Number
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 (N 2 )
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
Call recursive helper method
Merge Sort Start=0, end = 6, mid=(6+0)/2 = 3 Number
Merge Sort. Start=0, end = 3, mid=(3+0)/2 = 1. Start=4, end =6, mid=(4+6)/2=
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)