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,

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
MATH 224 – Discrete Mathematics
CSE Lecture 3 – Algorithms I
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 2D Arrays.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.
Data Structures Review Session 1
Algorithm Efficiency and Sorting
 Last lesson  Arrays for implementing collection classes  Performance analysis (review)  Today  Performance analysis  Logarithm.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Analysis of Algorithm.
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Chapter 8 ARRAYS Continued
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 19 Searching, Sorting and Big O
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
Applications of Arrays (Searching and Sorting) and Strings
Chapter 19: Searching and Sorting Algorithms
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
Array (continue).
CS1101: Programming Methodology Aaron Tan.
CSC 211 Data Structures Lecture 13
Data Structures Using C++ 2E Chapter 9 Searching and Hashing Algorithms.
Data Structure Introduction.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
CS1101: Programming Methodology
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Sorting and Searching. Searching  Problem definition: Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
16 Searching and Sorting.
Searching and Sorting 1-D Arrays
24 Searching and Sorting.
Chapter 11 Sorting and Searching
Presentation transcript:

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)