Presentation is loading. Please wait.

Presentation is loading. Please wait.

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,

Similar presentations


Presentation on theme: "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,"— Presentation transcript:

1 Array Search & Sort (continues)

2 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

3 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

4 Let’s work together Declare an array of 10 elements and initialize this array to even integers (starting from 0)

5 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.

6 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

7 Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information.

8 Declaring and Creating a 2-D Array Declaration [][] ; //variation 1 [][]; //variation 2 Creation = new [ ][ ] double[][] payScaleTable; payScaleTable = new double[4][5]; 3 2 1 0 43210 payScaleTable

9 Accessing an Element An element in a two-dimensional array is accessed by its row and column index.

10 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; }

11 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];

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

13 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 };.

14 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 };.

15 Example Use nested array initializers to initialize array1 Use nested array initializers of different lengths to initialize array2

16 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 ] ); 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

17 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

18 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.

19 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.

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

21 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)

22 Search Example: Number 40201817222730 X= 40 0 1 2 3 4 5 6 Return: 3

23 Search Example: Number 40201817222730 X= 32 0 1 2 3 4 5 6 Return: NOT_FOUND (-1)

24 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.

25 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)

26 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 }

27 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

28 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)

29 Example Unsorted array Sorted array Number 40201817222730 0 1 2 3 4 5 6 Number 22181720273040 0 1 2 3 4 5 6

30 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.

31 Sequence of Successful Search 512172338 4477 012345678 8490 search( 44 ) lowhighmid 0808 #1 high low 38 < 44 low = mid+1 = 5 mid 4

32 Sequence of Successful Search 512172338 4477 012345678 8490 search( 44 ) lowhighmid 0808 #1 44 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

33 Sequence of Successful Search - 3 512172338 4477 012345678 8490 search( 44 ) lowhighmid 0808 #1 44 == 44 4 5858 #2 6 highlow5 #3 mid 5 Successful Search!!

34 Sequence of Unsuccessful Search 512172338 4477 012345678 8490 search( 45 ) lowhighmid 0808 #1 high low 38 < 45 low = mid+1 = 5 mid 4

35 Sequence of Unsuccessful Search 512172338 4477 012345678 8490 search( 45 ) lowhighmid 0808 #1 45 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

36 Sequence of Unsuccessful Search 512172338 4477 012345678 8490 search( 45 ) lowhighmid 0808 #1 44 < 45 4 5858 #2 6 highlow5 #3 mid 5 low = mid+1 = 6

37 Sequence of Unsuccessful Search 512172338 4477 012345678 8490 search( 45 ) lowhighmid 0808 #1 4 5858 #2 65 #3 5 highlow 6565 #4 Unsuccessful Search low > high no more elements to search

38 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; }

39 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

40 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.

41 Comparing N and log 2 N Performance Array SizeLinear – NBinary – log 2 N

42 Project 2 discussion Customer name12 34 Total Hien Nguyen 32.96 0 0 0 32.96 ……. Tom Hanks0 199.99 0 200.10 400.09

43 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

44 “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

45 “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

46 “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 10 a. 6 b. 7 c. 8 d. 9

47 “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 10 a. 6 b. 7 c. 8 d. 9

48 “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 10 a. 1 b. 2 c. 3 d. 4

49 “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 10 a. 1 b. 2 c. 3 d. 4

50 “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)

51 “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)

52 Example X = 40? Number 22181720273040 0 1 2 3 4 5 6 Middle position = (6+0)/2 = 3 Comparing: 40 and number[3](22) => Not match =?

53 Example X = 40? Number 22181720273040 0 1 2 3 4 5 6 Middle position = (6+4)/2 = 5 Comparing: 40 and number[5](30) => Not match =?

54 Example X = 40? Number 22181720273040 0 1 2 3 4 5 6 Middle position = (6+6)/2 = 6 Comparing: 40 and number[6](40) => match Return 6

55 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.

56 Example Input: Output Number 40201817222730 0 1 2 3 4 5 6 Number 22181720273040 0 1 2 3 4 5 6

57 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

58 Example Input (unsorted): Input number 40201817222730 0 1 2 3 4 5 6 Number 0 1 2 3 4 5 6

59 Example First pass Number 40201817222730 0 1 2 3 4 5 6 Number 17 0 1 2 3 4 5 6 182040222730

60 Example Second pass Number 17 0 1 2 3 4 5 6 182040222730 Number 17 0 1 2 3 4 5 6 201840222730

61 Example Third pass Number 17 0 1 2 3 4 5 6 201840222730

62 Example Fourth pass Number 17 0 1 2 3 4 5 6 201840222730 Number 17 0 1 2 3 4 5 6 201822402730

63 Example Fifth pass Number 17 0 1 2 3 4 5 6 201822402730 Number 17 0 1 2 3 4 5 6 201822274030

64 Example Sixth pass Number 17 0 1 2 3 4 5 6 201822274030 Number 17 0 1 2 3 4 5 6 201822273040

65 Example Result Number 17 0 1 2 3 4 5 6 201822273040

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

67 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; }

68 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 )

69 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

70 Call recursive helper method

71

72

73

74

75

76

77

78

79 Merge Sort Start=0, end = 6, mid=(6+0)/2 = 3 Number 40201817222730 0 1 2 3 4 5 6 20184017 222730

80 Merge Sort. Start=0, end = 3, mid=(3+0)/2 = 1. Start=4, end =6, mid=(4+6)/2=5 2018 2227 30 4017

81 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)


Download ppt "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,"

Similar presentations


Ads by Google