24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 1 Class 16 - Searching r Linear search r Binary search r Binary search trees.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

COL 106 Shweta Agrawal and Amit Kumar
COP 3502: Computer Science I (Note Set #21) Page 1 © Mark Llewellyn COP 3502: Computer Science I Spring 2004 – Note Set 21 – Balancing Binary Trees School.
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
Binary Trees, Binary Search Trees COMP171 Fall 2006.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
AVL Trees / Slide 1 Balanced Binary Search Tree  Worst case height of binary search tree: N-1  Insertion, deletion can be O(N) in the worst case  We.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
David Luebke 1 7/2/2015 ITCS 6114 Binary Search Trees.
David Luebke 1 7/2/2015 Medians and Order Statistics Structures for Dynamic Sets.
Chapter 9 contd. Binary Search Trees Anshuman Razdan Div of Computing Studies
TCSS 342 BST v1.01 BST addElement To addElement(), we essentially do a find( ). When we reach a null pointer, we create a new node there. void addElement(Object.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Dictionaries CS 105. L11: Dictionaries Slide 2 Definition The Dictionary Data Structure structure that facilitates searching objects are stored with search.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
CSCE 3110 Data Structures & Algorithm Analysis Sorting (I) Reading: Chap.7, Weiss.
AVL Trees Neil Ghani University of Strathclyde. General Trees Recall a tree is * A leaf storing an integer * A node storing a left subtree, an integer.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSC 211 Data Structures Lecture 13
CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
Topic 19 Binary Search Trees "Yes. Shrubberies are my trade. I am a shrubber. My name is 'Roger the Shrubber'. I arrange, design, and sell shrubberies."
Data Structures Using C++ 2E Chapter 9 Searching and Hashing Algorithms.
Lecture – Searching a Tree Neil Ghani University of Strathclyde.
1 Searching Searching in a sorted linked list takes linear time in the worst and average case. Searching in a sorted array takes logarithmic time in the.
1 CSC 421: Algorithm Design & Analysis Spring 2013 Divide & conquer  divide-and-conquer approach  familiar examples: merge sort, quick sort  other examples:
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Data Structures and Algorithms TREE. Searching Sequential Searches Time is proportional to n We call this time complexity O(n) Pronounce this “big oh”
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
Dictionaries CS /02/05 L7: Dictionaries Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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,
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1 CompSci 105 SS 2006 Principles of Computer Science Lecture 17: Heaps cont.
AVL Trees An AVL tree is a binary search tree with a balance condition. AVL is named for its inventors: Adel’son-Vel’skii and Landis AVL tree approximates.
AVL Trees / Slide 1 Height-balanced trees AVL trees height is no more than 2 log 2 n (n is the number of nodes) Proof based on a recurrence formula for.
Binary Search Trees (BST)
Lecture 9COMPSCI.220.FS.T Lower Bound for Sorting Complexity Each algorithm that sorts by comparing only pairs of elements must use at least 
Binary Search Trees.  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement binary.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
8/3/2007CMSC 341 BTrees1 CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
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.
CSE 373 Binary search trees; tree height and balance
CSC 427: Data Structures and Algorithm Analysis
Efficiency of in Binary Trees
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
COMP 103 Binary Search Trees.
Representation of a Threaded Tree
CSE 373: Data Structures and Algorithms
CSE 373 Data Structures and Algorithms
CSC 143 Binary Search Trees.
Building Java Programs
Basic Data Structures - Trees
Tree.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CS 261 – Data Structures AVL Trees.
Presentation transcript:

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 1 Class 16 - Searching r Linear search r Binary search r Binary search trees

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 2 The problem r Given a set of data items {k 1, k 2,..., k n } - called keys - determine whether another key k occurs in the set. r (Variation: Start with pairs (k 1,v 1 ),..., (k n,v n ). Then given k, determine whether k = k i for some i; return v i.)

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 3 “Data structures” r We will consider two costs: m The cost of inserting the keys k i in some data structure (array, list, whatever) m The cost of searching for k r Cost depends primarily on how data are stored. r Best data structure can depend upon ratio of searches to insertions, how searches and insertions are distributed.

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 4 Data structures (cont.) r We will look at three data structures: m Linear storage in array - unsorted m Linear storage in array - sorted m Binary tree

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 5 Linear storage, unsorted Store data in array keys[0...count], unsorted 1. To insert key k : keys[count] = k; count++; 2. To find key k : for (i=0; i<count; i++) if (keys[i] == k) return i; Cost of inserting new key: O(1) Cost of searching for key: O(n)

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 6 Linear storage, sorted Store data in array keys[0...count], sorted 1. To insert key k : insert in correct order, as in insertion sort 2. To find key k : same as above Cost of inserting new key: O(n) Cost of searching for key: O(n)

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 7 Binary search Cost of searching in sorted array can be dramatically reduced by “divide and conquer”. boolean bsearch (int k, int[] keys, int i, int j) // find whether k occurs in keys[i..j]] Can cut size of subarray in half with one comparison:

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 8 Binary search (cont.) r Cases: m k == keys[m]: done m k < keys[m]: k occurs in keys[i..m-1] (if at all) m k > keys[m]: k occurs in keys[m+1..j] (if at all) keys i jm m = (j+i)/2

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 9 Binary search (cont.) boolean bsearch (int k, int[] keys, int i, int j) { // find whether k occurs in keys[i..j] int m = (i+j)/2; if (i > j) return false; if (k == keys[m]) return true; if (k < keys[m]) return bsearch(k, keys, i, m-1); return bsearch(k, keys, m+1, j); }

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 10 Efficiency of binary search # of comparisons = 2 * # of times array can be divided in half: log 2 n E.g. If n = 1,000,000, worst-case cost of linear search = 1,000,000; worst-case cost of binary search = 40.

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 11 Binary trees Can obtain log n insertions and searches (on average) by storing data in binary tree structure. Def. A binary tree is a structure consisting of a number (the label ) and two binary trees, the left and right subtrees. Both are optional.

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 12 Binary trees (cont.) Def. Size of tree t = number of nodes (i.e. numbers) in t.

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 13 Binary search trees r Def. A binary search tree (BST) is a binary tree with the following property: its label is greater than any of the labels in its left subtree and less than any labels in its right subtree. Furthermore, its left and right subtrees are binary search trees. r Example: tree on previous slide

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 14 Balanced BST’s r A binary search tree is balanced if its left and right subtrees are of approximately equal size, and are both balanced. r Def. The height of a tree is the length of the longest path from the top to the bottom. r Observation If a BST of size n is balanced, its height  log 2 n.

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 15 Searching in BST To find k in BST T = Cases: m k = k’: Done m k < k’: Search in T1 (if it exists) m k > k’: Search in T2 (if it exists) Time (in worst case) is proportional to height of T. If T is balanced, time is order log 2 n. k’ T1T2

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 16 Inserting in BST To insert k in BST T = Cases: m k = k’: Done (do nothing) m k < k’: Insert in T1. If T1 absent, add new left subtree containing just k m k > k’: Insert in T2. If T2 absent, add new right subtree containing just k If T is balanced, time is order log 2 n. k’ T1T2

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 17 Implementing BST’s r Represent trees by objects containing an integer and two references to other trees. (Recall that a reference to an object can be null, meaning it doesn’t really point to anything.) class BinarySearchTree { int val; BinarySearchTree left, right; BinarySearchTree (int v, BinarySearchTree l, BinarySearchTree r) { val = v; left = l; right = r; }

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 18 Implementing BST’s (cont.)  Could make the search and insert operations instance methods, but, as for lists, we will instead make them class methods of a separate class, BST. class BST { static BinarySearchTree makeBST (int k) { return new BinarySearchTree(k, null, null); }

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 19 Implementing BST’s (cont.) static boolean search (int k, BinarySearchTree t) { if (t == null) return false; else if (k == t.val) return true; else if (k < t.val) return search(k, t.left); else return search(k, t.right); }

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 20 Implementing BST’s (cont.) static void insert (int k, BinarySearchTree t) { // t must be non-null if (k == t.val) return; if (k < t.val) if (t.left == null) t.left = makeBST(k); else insert(k, t.left); else if (t.right == null) t.right = makeBST(k); else insert(k, t.right); }

24/3/00SEM107 - © Kamin & ReddyClass 16 - Searching - 21 Implementing BST’s (cont.) public static void main (String[] args) { BinarySearchTree T = BST.makeBST(7); BST.insert(3,T); BST.insert(5,T); BST.insert(13,T); BST.insert(11,T); BST.insert(9,T); BST.insert(1,T); System.out.print(BST.search(3, T)); // true System.out.print(BST.search(4, T)); // false } Here is an example of using these operations: