Binary search algorithm



Similar documents
Analysis of Binary Search algorithm and Selection Sort algorithm

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

Zabin Visram Room CS115 CS126 Searching. Binary Search

Binary Heap Algorithms

Computer Science 210: Data Structures. Searching

6. Standard Algorithms

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Searching Algorithms

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Lecture Notes on Linear Search

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

Loop Invariants and Binary Search

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

Chapter Objectives. Chapter 9. Sequential Search. Search Algorithms. Search Algorithms. Binary Search

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Lecture Notes on Binary Search Trees

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Chapter 7: Sequential Data Structures

Algorithms. Margaret M. Fleck. 18 October 2010

Analysis of a Search Algorithm

Outline. Introduction Linear Search. Transpose sequential search Interpolation search Binary search Fibonacci search Other search techniques

From Last Time: Remove (Delete) Operation

Binary Heaps. CSE 373 Data Structures

Lecture Notes on Binary Search Trees

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Data Structures. Algorithm Performance and Big O Analysis

DNS LOOKUP SYSTEM DATA STRUCTURES AND ALGORITHMS PROJECT REPORT

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Shortest Inspection-Path. Queries in Simple Polygons

Why Use Binary Trees?

Binary Trees and Huffman Encoding Binary Search Trees

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

4.2 Sorting and Searching

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Algorithms Chapter 12 Binary Search Trees

Section IV.1: Recursive Algorithms and Recursion Trees

recursion, O(n), linked lists 6/14

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Algorithms and Data Structures

The Goldberg Rao Algorithm for the Maximum Flow Problem

Sample Questions Csci 1112 A. Bellaachia

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

A Randomized Searching Algorithm and its Performance analysis with Binary Search and Linear Search Algorithms

How To Create A Tree From A Tree In Runtime (For A Tree)

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Binary Multiplication

Discrete Optimization

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

Quick Sort. Implementation

Many algorithms, particularly divide and conquer algorithms, have time complexities which are naturally

Big Data and Scripting. Part 4: Memory Hierarchies

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

GRID SEARCHING Novel way of Searching 2D Array

CS473 - Algorithms I

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

Algorithm Design and Recursion

Why you shouldn't use set (and what you should use instead) Matt Austern

Junghyun Ahn Changho Sung Tag Gon Kim. Korea Advanced Institute of Science and Technology (KAIST) Kuseong-dong, Yuseong-gu Daejoen, Korea

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

9th Max-Planck Advanced Course on the Foundations of Computer Science (ADFOCS) Primal-Dual Algorithms for Online Optimization: Lecture 1

Analysis of Algorithms I: Optimal Binary Search Trees

AP Computer Science AB Syllabus 1

Symbol Tables. Introduction

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

6 March Array Implementation of Binary Trees

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Heaps & Priority Queues in the C++ STL 2-3 Trees

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

APP INVENTOR. Test Review

MATHEMATICAL ENGINEERING TECHNICAL REPORTS. The Best-fit Heuristic for the Rectangular Strip Packing Problem: An Efficient Implementation

Classification - Examples

Chapter 6 Quantum Computing Based Software Testing Strategy (QCSTS)

CompSci-61B, Data Structures Final Exam

Battleships Searching Algorithms

Bounded Cost Algorithms for Multivalued Consensus Using Binary Consensus Instances

A Note on Maximum Independent Sets in Rectangle Intersection Graphs

>

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms

Algorithms and Data Structures Written Exam Proposed SOLUTION

Persistent Data Structures

Data Structure with C

Now is the time. For all good men PERMUTATION GENERATION. Princeton University. Robert Sedgewick METHODS

TWO ALGORITHMS FOR FAST INCREMENTAL TRANSITIVE CLOSURE OF SPARSE FUZZY BINARY RELATIONS

Cpt S 223. School of EECS, WSU

CS473 - Algorithms I

5. Binary objects labeling

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

The Mixed Binary Euclid Algorithm

Reminder: Complexity (1) Parallel Complexity Theory. Reminder: Complexity (2) Complexity-new

Transcription:

Binary search algorithm Definition Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Generally, to find a value in unsorted array, we should look through elements of an array one by one, until searched value is found. In case of searched value is absent from array, we go through all elements. In average, complexity of such an algorithm is proportional to the length of the array. Divide in half A fast way to search a sorted array is to use a binary search. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half. Performance The advantage of a binary search over a linear search is astounding for large numbers. For an array of a million elements, binary search, O(log N), will find the target element with a worst case of only 20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the element. Algorithm Algorithm is quite simple. It can be done either recursively or iteratively: 1. get the middle element; 2. if the middle element equals to the searched value, the algorithm stops; 3. otherwise, two cases are possible: o searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. o searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.

Now, we should define when iterations should stop? First case is when searched element is found. Second one is when subarray has no elements. In this case, We can conclude, that searched value doesn't present in the array. Illustration of Binary search X[12]: Search for b=12 mid = (0+11)/2 = 5. Compare b with X[5]: 12<20. So search in left half X[0..4] mid = (0+4)/2 = 2. Compare b with X[2]: 12 > 7. So search right half X[3..4] mid = (3+4)/2 = 3.Compare b with X[3]: b=x[3]=12. Return 3.

The Recursive Code of Binary Search int binarysearch(double b, double X[], int left, int right) { if (left == right) if (b==x[left]) return left; else return -1; int mid = (left+right)/2; if (b==x[mid]) return mid; if (b < X[mid]) return binarysearch (b, X, left, mid-1); if (b > X[mid]) return binarysearch(b, X, mid+1, right); Example 1. Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114. Step 1 (middle element is 19 > 6): -1 5 6 18 19 25 46 78 102 114 Step 2 (middle element is 5 < 6): -1 5 6 18 19 25 46 78 102 114 Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114 Example 2. Find 103 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114. Step 1 (middle element is 19 < 103): 1 5 6 18 19 25 46 78 102 114 Step 2 (middle element is 78 < 103): 1 5 6 18 19 25 46 78 102 114 Step 3 (middle element is 102 < 103): 1 5 6 18 19 25 46 78 102 114 Step 4 (middle element is 114 > 103): 1 5 6 18 19 25 46 78 102 114 Step 5 (searched value is absent): 1 5 6 18 19 25 46 78 102 114

/* * searches for a value in sorted array * arr is an array to search in * value is searched value * left is an index of left boundary * right is an index of right boundary * returns position of searched value, if it presents in the array * or -1, if it is absent */ int binarysearch(int arr[], int value, int left, int right) { while (left <= right) { int middle = (left + right) / 2; // compute mid point. if (arr[middle] == value) return middle; // found it. return position else if (arr[middle] > value) else right = middle - 1; // repeat search in bottom half. left = middle + 1; // repeat search in top half. return -1;

Example int binarysearch(int sortedarray[], int first, int last, int key) { // function: // Searches sortedarray[first]..sortedarray[last] for key. // returns: index of the matching element if it finds key, // otherwise -(index where it could be inserted)-1. // parameters: // sortedarray in array of sorted (ascending) values. // first, last in lower and upper subscript bounds // key in value to search for. // returns: // index of key, or -insertion_position -1 if key is not // in the array. This value can easily be // transformed into the position to insert it. while (first <= last) { int mid = (first + last) / 2; // compute mid point. if (key > sortedarray[mid]) first = mid + 1; // repeat search in top half. else if (key < sortedarray[mid]) last = mid - 1; // repeat search in bottom half. else return mid; // found it. return position ///// return -(first + 1); // failed to find key Complexity analysis Huge advantage of this algorithm is that its complexity depends on the array size logarithmically in worst case. In practice it means, that algorithm will do at most log2(n) iterations, which is a very small number even for big arrays. It can be proved very easily. Indeed, on every step the size of the searched part is reduced by half. Algorithm stops, when there are no elements to search in. The binary search algorithm time complexity is O(log2(n)).