Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms.

Similar presentations


Presentation on theme: "Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms."— Presentation transcript:

1 Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms

2 2 Searching algorithms Linear search: sorted and unsorted array Binary search: sorted array

3 3 Search Concept

4 4 Linear Search

5 5 Unsorted List

6 6 Algorithm for Linear Search (Unsorted Array) Go through the array comparing the item required with the item in the array at each position If item is not found state this If item is found state position of item Number of comparisons: Average for successful search = number of elements/2 (n/2) Unsuccessful search = number of elements (n) O (n) Performance = O (n)

7 7 Linear Search (Another Algorithm) int LinearSearch(int [] array, int item) { //local variable to store position of required item set initially to –1 int place = -1; int index = 0; //Go through array till whole array searched or item found while ( index < array.length) { //check if item is found, and if so set place accordingly if ( array[index] == item) place = index; else index++; } //Return the item’s place in the array return place; } while ( index < array.length && place == -1) {

8 8 /*Linear (Sequential) Search algorithm for finding an element in the array. If the search element is found, it returns the position(index) of the element. otherwise, it return -1. */ public int LinearSearch(int v) { inti=0, iv = -1; while( i < NElements && iv == -1 ) { if( A[i] == v ) iv = i; i++; } return iv; //iv is either index of the found element or -1 } Linear Search Code for Linear Search (Unsorted Array)

9 9 Binary Search

10 10 Binary Search Algorithm int Binary Search (Array A, item v) int first = 0, last = n-1, mid, found =-1; while (first <= last and found == -1) mid = (first+last)/2; if A[mid] == v then found = mid; else if A[mid] < v then first = mid +1; else last = mid -1; end while return (found) end Binary Search What is the order of magnitude of the time performance for binary search? O(Log 2 n) Binary Search

11 11 Exercise Implement Binary search using Java and test it using a testing program of your design. Run feeding array + search item Print the run time

12 12 Binary Search program

13 13


Download ppt "Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms."

Similar presentations


Ads by Google