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)



Similar documents
Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Binary Heap Algorithms

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

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

Converting a Number from Decimal to Binary

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

Binary Heaps. CSE 373 Data Structures

Analysis of Algorithms I: Binary Search Trees

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Binary Search Trees CMPSC 122

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

6 March Array Implementation of Binary Trees

External Sorting. Chapter 13. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

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

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Persistent Binary Search Trees

Analysis of Binary Search algorithm and Selection Sort algorithm

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

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Cpt S 223. School of EECS, WSU

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

AP Computer Science AB Syllabus 1

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

External Sorting. Why Sort? 2-Way Sort: Requires 3 Buffers. Chapter 13

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

CS473 - Algorithms I

Binary Trees and Huffman Encoding Binary Search Trees

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Data Structures. Level 6 C Module Descriptor

APP INVENTOR. Test Review

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

Exam study sheet for CS2711. List of topics

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

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

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:

Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)

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

Algorithms and Data Structures

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

A Comparison of Dictionary Implementations

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

CS711008Z Algorithm Design and Analysis

DNS LOOKUP SYSTEM DATA STRUCTURES AND ALGORITHMS PROJECT REPORT

Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).

Randomized algorithms

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

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Zabin Visram Room CS115 CS126 Searching. Binary Search

1/1 7/4 2/2 12/7 10/30 12/25

Lecture 1: Data Storage & Index

Algorithms. Margaret M. Fleck. 18 October 2010

Algorithms Chapter 12 Binary Search Trees

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

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,

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Full and Complete Binary Trees

Data Structures. Algorithm Performance and Big O Analysis

Data Structures in the Java API

Big Data and Scripting. Part 4: Memory Hierarchies

Quick Sort. Implementation

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

CS473 - Algorithms I

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

Load Balancing. Load Balancing 1 / 24

Data Structure [Question Bank]

Lecture 1: Course overview, circuits, and formulas

Scalable Prefix Matching for Internet Packet Forwarding

Partitioning and Divide and Conquer Strategies

Domains and Competencies

Data storage Tree indexes

Cloud and Big Data Summer School, Stockholm, Aug., 2015 Jeffrey D. Ullman

Binary search algorithm

Day 1. This is CS50 for MBAs. Harvard Busines School. Spring Cheng Gong

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

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

The ADT Binary Search Tree

Computer. Course Description

Algorithms and Data Structures Written Exam Proposed SOLUTION

DATA STRUCTURES USING C

Ordered Lists and Binary Trees

2) What is the structure of an organization? Explain how IT support at different organizational levels.

6. Standard Algorithms

Why? A central concept in Computer Science. Algorithms are ubiquitous.

IMPROVING PERFORMANCE OF RANDOMIZED SIGNATURE SORT USING HASHING AND BITWISE OPERATORS

SIMS 255 Foundations of Software Design. Complexity and NP-completeness

Persistent Data Structures and Planar Point Location

Binary Search Trees. Ric Glassey

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

From Last Time: Remove (Delete) Operation

CS 300 Data Structures Syllabus - Fall 2014

Chapter 13: Query Processing. Basic Steps in Query Processing

B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

ML for the Working Programmer

CSE 326: Data Structures B-Trees and B+ Trees

Basic Programming and PC Skills: Basic Programming and PC Skills:

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

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

Transcription:

Sorting revisited How did we use a binary search tree to sort an array of elements? Tree Sort Algorithm Given: An array of elements to sort 1. Build a binary search tree out of the elements 2. Traverse the tree in- order and copy the elements back into the array. Runtime: Worst-case: When does the worst-case runtime occur? It occurs when the binary search tree is unbalanced, for example when the data is already sorted. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2) Best-case: Build the binary search tree: O(n log n) Traverse the binary tree: O(n) Total: O(n log n) + O(n) = O(n log n) Of what sort does tree sort remind you? Quicksort The first element is the pivot, which is used to partition the elements into those less than the pivot and those greater than the pivot Recursively apply quicksort to the two partitions: The first element less than the pivot becomes the pivot for partitioning in the recursive call. Similarly for the elements greater than the pivot. Tree sort The first element becomes the root of the tree. All elements are compared with the root and are separated into those less than the root and those greater than the root Building the left and right subtree corresponds to the recursive calls in quicksort. The elements and size of the left and right subtrees are the same as the two partitions: The first element less than the root becomes the root of the left subtree and all elements in that subtree are separated by the left subtree root. Similarly with the right subtree.

What distinguishes Quicksort from Tree sort? Quicksort In- place (uses only the original array) It can attempt to balance by picking a random pivot, in which case O(n log n) expected worst- case runtime Tree sort Extra memory space for the tree Can maintain balance to avoid worst- case behavior, in which case O(n log n), guaranteed worst- case runtime Can you use TreeSet to implement Tree Sort? Only if you have don't have duplicates. How can you use TreeMap to implement Tree Sort. Use map to a count of the duplicated elements. Then duplicate the element that number of times when you copy back to the array. Recall: Which sorting algorithm is always slow O(n^2)? Selection sort Which sorting algorithm is sometimes O(n)? Insertion sort What sort runs in O(log n)? None! Need to look at each element at a minimum! What other sorts are O(n log n) expected time? Quicksort, Merge sort. Which sorting algorithm needs extra memory space? Merge sort, Tree sort Can we do better than doing O(n log n) comparisons to sort? No! Theorem: There is no sorting algorithm that uses less than Ω(n log n) comparisons (lower bound) on some input. That is, for any sorting algorithm, there is always some permutation of the input that forces the sorting algorithm to make at least n log n comparisons.

How did the student sort the deck of n playing cards by color, so that all the red cards appear before the black cards? 1. Go through the deck and put each card into one of two piles, red and black. 2. Move the red cards and then the black cards into a single pile. What is the run time? Part 1: O(n) Part 2: O(n) Overall: O(n) Can we sort a deck of n cards by suit the same way? Make 4 piles, one for each suit. Still O(n) runtime. Can we sort a deck of n cards by rank in the same way? Make 13 piles. What is the runtime? O(n) Could there be an ordering of the cards that would take longer? No, it s always O(n). Can we sort n integers all in the range 1 to 100 in O(n) time? Yes. Make 100 piles. How can that be? Isn't sorting supposed to be at least Ω (n log n)? It is, but only if you sort by comparing one value with another value. All the other sorts we seen so far are comparison- based sorts. When sorting the playing cards we just put the values into the correct pile (buckets) without comparing one value against another. Bucket Sort (aka Pigeonhole sort) Let k be the range of values of the elements being sorted, where each value is discrete. Algorithm 1. Create an array of k buckets, one for each possible discrete value. 2. Copy each element to its unique bucket by computing the bucket s index. Keep all the values within a bucket in a linked list. 3. For each bucket in order from smallest to largest value, copy each element within the bucket back to the input array. Bucket sort is similar to hashing where hash function is, h(xi) = Xi. That is, insert into bucket equal to the element value.

What is the runtime to sort n elements using Bucket Sort? 1. O(k) 2. O(n) 3. O(k) to iterate over the k buckets + O(n) to copy each card from the linked lists to the array But Overall: O(k + n). If k = O(n), Bucket sort is linear! Restriction: Can only be use when the values are discrete and you know the range of values before sorting. There is no such restriction for comparison- based sorts.

Priority Queues What data structure has the following operations? isempty add - add at end remove - remove at front peek - at front Answer: Queue What happens when you go to the emergency room? Do they use a queue? No. If you have a serious life- threatening condition, you immediately get in the front of the queue. The queuing paradigm for the emergency room is each person is given a priority and the person with the highest priority goes first. Examples of a priority queue: Print queue for a printer: Smaller printouts have higher priority than larger printouts. Process scheduling on a computer: Process that tracks the mouse and displays it on the computer screen has higher priority than a process that is getting email from an Internet server. Priority Queue has the following operations: isempty() add (with priority) remove (highest priority) peek (at highest priority) What is the worst-case runtime for the following implementations of a priority queue? Implementation add peek array O(1) O(n) linked list O(1) O(n) sorted array O(n) O(1) array of linked lists O(1) O(k)* binary search tree O(n) O(n) balance binary search tree O(log n) O(log n) heap O(log n) O(1) * k is the number of distinct priorities.