Kruse/Ryba Ch071 Object Oriented Data Structures Searching STL Vector Sequential Search Binary Search Comparison Trees.

Slides:



Advertisements
Similar presentations
Zabin Visram Room CS115 CS126 Searching
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
Binary Searching.
HST 952 Computing for Biomedical Scientists Lecture 9.
Chapter 7 Chapter 7 SEARCHING`. Outline 1. Introduction, Notation 2. Sequential Search 3. Binary Search 4. Comparison Trees 5. Lower Bounds 6. Asymptotics:
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
1 Standard Containers: Lists Gordon College Resource:
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
Searching Arrays Linear search Binary search small arrays
C++ for Engineers and Scientists Third Edition
1 Data Structures CSCI 132, Spring 2014 Lecture 22 Searching.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using C++ 2E
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
1 Sorting Algorithms (Basic) Search Algorithms BinaryInterpolation Big-O Notation Complexity Sorting, Searching, Recursion Intro to Algorithms Selection.
Chapter 16: Searching, Sorting, and the vector Type.
Searching Chapter 7. Objectives Introduce sequential search. – Calculate the computational complexity of a successful search. Introduce binary search.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Applications of Arrays (Searching and Sorting) and Strings
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
CSC 211 Data Structures Lecture 13
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
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.
Introduction to Algorithms: Verification, Complexity, and Searching (2) Andy Wang Data Structures, Algorithms, and Generic Programming.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
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.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
1 Queues Queue API Application: Radix Sort Implementation: Using Deque Using Deque Circular Array Circular Array Priority Queue Priority Queue API Implementation.
Introduction to Algorithms: Verification, Complexity, and Searching Andy Wang Data Structures, Algorithms, and Generic Programming.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
CS212: DATASTRUCTURES Lecture 3: Searching 1. Lecture Contents  searching  Sequential search algorithm.  Binary search algorithm. 2.
1 Discrete Structures – CNS2300 Text Discrete Mathematics and Its Applications Kenneth H. Rosen (5 th Edition) Chapter 2 The Fundamentals: Algorithms,
Searching ( 搜索) 1. Introduction 2. Sequential Search 3. Binary Search 4. Comparison Trees.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
1 Data Structures CSCI 132, Spring 2014 Lecture23 Analyzing Search Algorithms.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Vectors Holds a set of elements, like an array
Trees 1: Theory, Models, Generic Heap Algorithms, Priority Queues
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Chapter 9 One-Dimensional Arrays
Elements are always copied when they are put into a container
Lists - I The List ADT.
Lists - I The List ADT.
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Kruse/Ryba Ch071 Object Oriented Data Structures Searching STL Vector Sequential Search Binary Search Comparison Trees

Kruse/Ryba ch072 Searching

Kruse/Ryba ch073 The STL vector Template template class vector { public: typedef T * iterator; typedef T value_type; // constructors vector (unsigned int numberElements); vector (unsigned int numberElements, T initialValue); vector (const vector & source); vector ();

Kruse/Ryba ch074 The STL vector template // member functions T back (); iterator begin (); int capacity (); bool empty(); iterator end (); T front (); void pop_back (); void push_back (T); void reserve (unsigned int); void resize (unsigned int); int size ();

Kruse/Ryba ch075 The STL vector template // operators T & operator [ ] (unsigned int); protected: // data areas unsigned int mySize; unsigned int myCapacity T * data; };

Kruse/Ryba ch07 template class orderedVector public vector { public: // constructors orderedVector : vector (){} orderedVector( orderedVector & v): vector (v){} // additional methods T & operator [ ] (unsigned int index) const; // protocol for searching int count (T & value); void find (T & value); void insert (T & value); void erase (T & value); };

Kruse/Ryba ch077 Declaring Template Types To declare a value with a template type, a type is provided in angle brackets following the template class name. vector a(10); vector b(30); vector c(15, “xyz”);

Kruse/Ryba ch078 Summary of STL Vector Operations vector v; default vector v(int); init,size vector v(int, T); size,valu vector v(aVector); copy Constructors

Kruse/Ryba ch079 v[i]subscript v.front() first v.back()last Element Access Summary of STL Vector Operations

Kruse/Ryba ch0710 v.push_back (T) – push on to back of vector v.insert(iterator, T) – insert before iterator v.swap(vector ) – swap values with another vector Insertion Summary of STL Vector Operations

Kruse/Ryba ch0711 v.pop_back – pop from back of vector v.erase(iterator) – remove single element v.erase(iterator, iterator) – remove range of values Removal Summary of STL Vector Operations

Kruse/Ryba ch0712 v.capacity () max v.size ()current v.resize(unsigned, T) v.reserve (unsigned) v.empty () Size Summary of STL Vector Operations

Kruse/Ryba ch0713 vector ::iterator itr – declare a new iterator v.begin() – starting iterator v.end() – ending iterator Summary of STL Vector Operations

Kruse/Ryba ch0714 Generic Algorithms fill(iterator start, iterator stop, value) copy (iterator start, iterator stop, iterator destination) max_element(iterator start, iterator stop) min_element(iterator start, iterator stop) reverse(iterator start, iterator stop) count(iterator start, iterator stop, target value, counter)

Kruse/Ryba ch0715 Generic Algorithms count_if(iterator start, iterator stop, unary fun, counter) transform(iterator start, iterator stop, iterator destination, unary) find(iterator start, iterator stop, value) find_if(iterator start, iterator stop, unary function) replace(iterator start, iterator stop, target value, replacement value)

Kruse/Ryba ch0716 Generic Algorithms replace_if(iterator start, iterator stop, unary fun, replacement val) sort(iterator start, iterator stop) for_each(iterator start, iterator stop, function) iter_swap(iterator, iterator)

Kruse/Ryba ch0717 Generic Algorithms -sorted merge(iterator s1, iterator e1, iterator s2, iterator e2, iterator destination) inplace_merge(iterator start, iterator center, iterator stop) binary_search(iterator start, iterator stop, value)

Kruse/Ryba ch0718 Generic Algorithms - sorted lower_bound(iterator start, iterator stop, value) upper_bound(iterator start, iterator stop, value)

Kruse/Ryba ch07 Application - Root Finding The idea of binary search can also be used in different circumstances where the algorithm does not necessarily apply. 0 08

Kruse/Ryba ch07 Application - Root Finding The idea of binary search can also be used in different circumstances where the algorithm does not necessarily apply

Kruse/Ryba ch07 Application - Root Finding The idea of binary search can also be used in different circumstances where the algorithm does not necessarily apply.

Kruse/Ryba ch07 Application - Root Finding The idea of binary search can also be used in different circumstances where the algorithm does not necessarily apply.

Kruse/Ryba ch07 Application - Root Finding The idea of binary search can also be used in different circumstances where the algorithm does not necessarily apply.

Kruse/Ryba ch

02 0 1

Kruse/Ryba ch

Kruse/Ryba ch

Kruse/Ryba ch07 Binary Search For this algorithm to work, the data must be sorted in the array.

Kruse/Ryba ch07 Binary Search Suppose the item of interest has value 62! The algorithm finds the midpoint of the array (0+11)/2 = 5 and looks in that position. If the item is found, the search is over

Kruse/Ryba ch07 Binary Search In this case, the item wasn’t found. However, since the array is sorted and 62 > 45, we know it should be below the midpoint, if it exists. We now look at the midpoint of what is left by calculating the index (6+11)/2 = 8, and look there.

Kruse/Ryba ch07 Binary Search If the item is found, the search is over. In this case, the search goes on.

Kruse/Ryba ch07 Binary Search We know 62 < 67 so we should restrict our search to the portion above that has not been searched. If we recalculate the search index (6+7)/2=6 we see that we are narrowing down on the location.

Kruse/Ryba ch07 Binary Search But, we are still not there. There is really only one place left to look but the algorithm doesn’t know this. It only knows that 62>55 so it should look below the current location.

Kruse/Ryba ch07 Binary Search One final calculation of the index (7+7)/2 = 7 leads us to the location we have been looking for. Note that we only repeated the process and comparison four times (looking in 5, 8, 6, 7) and that is pretty good when there are actually 11 cells.

Kruse/Ryba ch07 A Simple but Subtle Idea Although binary search is a simple and obvious idea, it is surprisingly easy to code incorrectly. You really need invariants to provide correctness. Invariant : low is the index of the smallest value that could possibly match the target. high is the index of the first element that is definitely larger than target, or is one element larger than the size of the vector if all elements are smaller than target. Algorithm proceeds by examining midpoint, and changing either low or high so as to preserve invariants.

Kruse/Ryba ch0737 STL Binary Search bool binary_search(iterator start, iterator stop, value);

Kruse/Ryba ch0738 Error_code recursive_binary_1(const Ordered_list &the_list, const Key &target,int bottom, int top, int &position) { Record data; if (bottom < top) {// List has more than one entry. int mid = (bottom + top) / 2; the_list.retrieve(mid, data); if (data < target) // Reduce to top half of list. return recursive_binary_1(the_list, target, mid + 1, top, position); else // Reduce to bottom half of list. return recursive_binary_1(the_list, target, bottom, mid, position); } else if (top < bottom) return not_present; // List is empty. else { // List has exactly one entry. position = bottom; the_list.retrieve(bottom, data); if (data == target) return success; else return not_present; } }

Kruse/Ryba ch0739 Error_code recursive_binary_2(const Ordered_list &the_list, const Key &target, int bottom, int top, int &position) { Record data; if (bottom <= top) { int mid = (bottom + top) / 2; the_list.retrieve(mid, data); if (data == target) { position = mid; return success; } else if (data < target) return recursive_binary_2(the_list, target, mid + 1, top, position); else return recursive_binary_2(the_list, target, bottom, mid - 1, position); } else return not_present; }

Kruse/Ryba ch0740 Order of Magnitude

Kruse/Ryba ch0741 nlog nnnlog nn 2 2 n n! 103E-9E-83E-8E-7E-63E E-9E-77E-7E-54E13yr * E-8E-6E-5E-3 * * E-8E-5E-4E-1 * * E-8E-42E-310 * * E-8E-32E-217min * * All times are in seconds unless otherwise stated. An * indicates a time of more than years. Computer Times Used by Algorithms

Kruse/Ryba ch0742 Order of Magnitude

Kruse/Ryba ch0743 class Key, Used for Comparisons class Key { int x; public: static int comparisons; Key(int x = 0); int the_key() const; };

Kruse/Ryba ch0744 class Key Comparison Operators // Declare overloaded comparison operators bool operator ==(const Key &x, const Key &y); bool operator > (const Key &x, const Key &y); bool operator =(const Key &x, const Key &y); bool operator <=(const Key &x, const Key &y); bool operator !=(const Key &x, const Key &y);

Kruse/Ryba ch0745 Overloading Operators bool operator ==(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() == y.the_key(); }

Kruse/Ryba ch0746 void test_search(int searches, List &the_list) { int list_size = the_list.size(); if (searches <= 0 || list_size < 0) { cout << " Exiting test: " << endl << " The number of searches must be positive." << endl; << " The number of list entries must exceed 0." << endl; return; } int i, target, found_at; Key::comparisons = 0; Random number; Timer clock; for (i = 0; i < searches; i++) { target = 2 * number.random_integer(0, list_size - 1) + 1; if (sequential_search(the_list, target, found_at) == not_present) cout << "Error: Failed to find expected target " << target << endl; }

Kruse/Ryba ch0747 print_out("Successful", clock.elapsed_time(), Key::comparisons, searches); Key::comparisons = 0; clock.reset(); for (i = 0; i < searches; i++) { target = 2 * number.random_integer(0, list_size); if (sequential_search (the_list, target, found_at) == success) cout << "Error: Found unexpected target " << target << " at " << found_at << endl; } print_out("Unsuccessful", clock.elapsed_time(), Key::comparisons, searches); }

Kruse/Ryba ch0748 Chapter 7 Ends