CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun.

Slides:



Advertisements
Similar presentations
CSE Lecture 3 – Algorithms I
Advertisements

1 Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances.
CS4413 Divide-and-Conquer
1 Merge Sort Review of Sorting Merge Sort. 2 Sorting Algorithms Selection Sort uses a priority queue P implemented with an unsorted sequence: –Phase 1:
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
Theory of Algorithms: Divide and Conquer
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 5.
Analysis of Algorithms CS 477/677 Sorting – Part B Instructor: George Bebis (Chapter 7)
Spring 2015 Lecture 5: QuickSort & Selection
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
CS 253: Algorithms Chapter 7 Mergesort Quicksort Credit: Dr. George Bebis.
Chapter 4: Divide and Conquer The Design and Analysis of Algorithms.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Merge sort, Insertion sort
Analysis of Algorithms CS 477/677 Midterm Exam Review Instructor: George Bebis.
TDDB56 DALGOPT-D DALG-C Lecture 8 – Sorting (part I) Jan Maluszynski - HT Sorting: –Intro: aspects of sorting, different strategies –Insertion.
Sorting Chapter 10.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
Algorithm Efficiency and Sorting
Merge sort, Insertion sort. Sorting I / Slide 2 Sorting * Selection sort or bubble sort 1. Find the minimum value in the list 2. Swap it with the value.
CSC 2300 Data Structures & Algorithms March 20, 2007 Chapter 7. Sorting.
CS Main Questions Given that the computer is the Great Symbol Manipulator, there are three main questions in the field of computer science: What kinds.
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances.
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Reynolds 2006 Complexity1 Complexity Analysis Algorithm: –A sequence of computations that operates on some set of inputs and produces a result in a finite.
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Copyright © 2007 Pearson Addison-Wesley. All rights reserved. A. Levitin “ Introduction to the Design & Analysis of Algorithms, ” 2 nd ed., Ch. 1 Chapter.
CSCE 3110 Data Structures & Algorithm Analysis Sorting (I) Reading: Chap.7, Weiss.
1 Lecture 16: Lists and vectors Binary search, Sorting.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Sorting Chapter 10. Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following sorting.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
Heapsort. Heapsort is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
1 Sorting (Bubble Sort, Insertion Sort, Selection Sort)
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
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.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
Sorting. Sorting Sorting is important! Things that would be much more difficult without sorting: –finding a telephone number –looking up a word in the.
2IS80 Fundamentals of Informatics Fall 2015 Lecture 6: Sorting and Searching.
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
1 Ch. 2: Getting Started. 2 About this lecture Study a few simple algorithms for sorting – Insertion Sort – Selection Sort (Exercise) – Merge Sort Show.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Sorting.
CSC317 1 So far so good, but can we do better? Yes, cheaper by halves... orkbook/cheaperbyhalf.html.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 23 Sorting.
Prof. U V THETE Dept. of Computer Science YMA
Searching and Sorting Algorithms
Sorting With Priority Queue In-place Extra O(N) space
Divide and Conquer.
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Binary Search Back in the days when phone numbers weren’t stored in cell phones, you might have actually had to look them up in a phonebook. How did you.
8/04/2009 Many thanks to David Sun for some of the included slides!
Sorting Chapter 10.
Presentation transcript:

CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun

Sort Since the dawn of computing, sorting has attracted a great deal of attention due to the complexity of solving it efficiently despite the simple problem statement. A sorting algorithm is an algorithm that puts the elements of a list in a certain order: numerical order or lexicographical order. Sorting supports basic searching: – for a number in a phone book – a website with the most relevant information to your search query. Sorting is perhaps the simplest fundamental problem that offers a large variety of algorithms, each with its own inherent advantages and disadvantages.

Bubble Sort Simple idea: – Step through the list to be sorted, compare adjacent elements, swap them if they are in the wrong order. – Repeat the pass through the list until no swaps are needed. – Invariant: after the kth iteration, the k-largest elements are at the end of the list. An example.

How Good Is Bubble Sort? Let’s hear what Senator Obama has to say

Bubble Sort Although simple to understand and implement, has worst case O(n 2 ) running time, which means it is far too inefficient for practical usage. The generic bad algorithm: – "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems“ – Donald Knuth

Insertion Sort Simple idea: – Starting with empty sequence of outputs S and the unsorted list of n input items I. – Add each item from input I, inserting into output sequence S at a position so the output is still in sorted order. – Invariant: at the kth iteration, the elements from 0 to k-1 in the output sequence S are sorted. An example

Insertion Sort If destination is a linked list – Theta(n) worst-case time to find the right position of S to insert each item. – Theta(1) time to insert the item. If destination is an array – Find the right position in S in O(log n) time by binary search. – Theta(n) worst-case time to shift the larger items over to make room for the new item.

In-place Insertion Sort If S is an array, we can do an in place sort: – Store sorted items in the same array that initially held the input items – Partition the array into two pieces: the left portion (initially empty) holds S, and the right portion holds I. – With each iteration, the dividing line between S and I moves one step to the right.

Running time What’s the best case? – Sorted array: just compare the first remaining element of the input against the last element of the sorted subsection of the array. – The running time is proportional to the number of inversions. – Runs in O(n) where n is the number of elements. What’s the worst-case? – Inversely sorted array: every iteration, you need to scan and shift the entire sorted portion of the array before inserting the next element. – O(n 2 ) where n is the number of elements.

Insertion Sort Using Binary Search Tree You can use binary search tree to store the output: – Insertion into the binary search tree is O(log n), so insertion sort takes O(n log n). – But there are better O(n log n) alternatives.

Selection Sort Simple idea: – Starting with empty output S and the unsorted list of n input items I. – Walk through I and find the smallest item, remove the item and append to the end of the output S. – Invariant: at the kth iteration, the k smallest elements of the input I are sorted. An example.

Selection Sort v.s Insertion Sort At the kth iteration – Selection sort must find the smallest item in the remaining list: selecting the lowest element requires scanning all n elements. Finding the next lowest element requires scanning the remaining n - 1 elements : (n - 1) + (n - 2) = n(n - 1) / 2 = Θ(n 2 ). so selection sort takes Theta(n 2 ) time, even in the best case. – Insertion sort only examines the sorted portion of the list, so on average it examines half as many elements. For the best case, it only examines the right most element in the sorted part of the list.

In-place Selection Sort If S is an array, we can do an in-place selection sort. Divide the list into two parts: – the sublist of items already sorted, which we build up from left to right and is found at the beginning, and – the sublist of items remaining to be sorted, occupying the remainder of the array. – After finding the item in I having smallest key, swap it with the first item in I. An example.

Heapsort Heapsort is a selection sort in which I is a heap. 1.Start with an empty list S and an unsorted list I of n input items 2.Put all the items in I onto an array and perform bottomUpHeap() 3.At each iteration, remove the max or min element from the heap while maintaining the heap property; append the element at the end of S bottomUpHeap() runs in linear time, and each removeMin() takes O(log n) time. Hence, heapsort is an O(n log n) sorting algorithm, even in the worst case.

Heapsort Heapsort can be implemented in-place using an array to achieve constant time space overhead. – Store the heap in reverse order. – As items are removed from the heap, the heap shrinks toward the end of the array, making room to add items to the end of S. An Example. Heapsort relies strongly on random access, so it excellent for sorting arrays, but not so for linked lists. – One can turn a linked list into an array. Sort the array of listnode references. When the array is sorted, link all the listnodes together into a sorted list.

Merge Two Sorted Lists Observation: one can merge two sorted lists into one sorted list in linear time. Psuedocode: Let Q1 and Q2 be two sorted queues. Let Q be an empty queue. merge(Q, Q1, Q2) { while (neither Q1 nor Q2 is empty) { item1 = Q1.front(); item2 = Q2.front(); move the smaller of item1 and item2 from its present queue to end of Q. } concatenate the remaining non-empty queue (Q1 or Q2) to the end of Q. } merge(Q, Q1, Q2) takes O(n) time.

Recurrence (not examable) When an algorithm contains a recursive call to it self, the running time can be described using a recursive relation - describing the running time of a problem of size n in terms of running time of smaller inputs. General framework: – Let T(n) be the running time on a problem of size n – The problem is divided into a subproblems, each of which is 1/b in size. – If it takes D(n) time to divide he problem into subproblems – If it takes C(n) time to combine the solutions to the subproblems: – T(n) = a * T(n/b) + D(n) + C(n) if n >= c(constant)

Mergesort Mergesort is a recursive divide-and-conquer algorithm: 1.Start with the unsorted list I of n input items. 2.If n is 0 or 1 then it is sorted. Otherwise: 3.Break I into two halves I1 and I2 of about half the size. 4.Sort I1 recursively, yielding the sorted list S1. 5.Sort I2 recursively, yielding the sorted list S2. 6.Call merge() to put S1 and S2 into a sorted list S. What’s the time complexity of Mergesort? – Each recursive call involves O(n) operations, and there are O(log n) recursive calls – Mergesort runs in O(n log n).

Mergesort Mergesort and heapsort are both O(n log n), Mergesort requires Theta(n) additional space compared to Theta(1) for heapsort. Mergesort is efficient for linked lists. Mergesort is not an in-place algorithm. – There are ways to do it, but very complicated and offer little performance gains.

Readings Objects, Abstraction, Data Structures and Design – Chapter 10 pp519 – 522 pp525 – 529 pp