Programming Abstractions Cynthia Lee CS106X. Today’s Topics Sorting! 1.The warm-ups  Selection sort  Insertion sort 2.Let’s use a data structure! 

Slides:



Advertisements
Similar presentations
Sorting CMSC 201. Sorting In computer science, there is often more than one way to do something. Sorting is a good example of this!
Advertisements

Sorting Algorithms Bryce Boe 2012/08/13 CS32, Summer 2012 B.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
CS 112 Introduction to Programming Sorting of an Array Debayan Gupta Computer Science Department Yale University 308A Watson, Phone:
HST 952 Computing for Biomedical Scientists Lecture 9.
Quicksort CSE 331 Section 2 James Daly. Review: Merge Sort Basic idea: split the list into two parts, sort both parts, then merge the two lists
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CSE 373: Data Structures and Algorithms
Data Structures Data Structures Topic #13. Today’s Agenda Sorting Algorithms: Recursive –mergesort –quicksort As we learn about each sorting algorithm,
Sorting Algorithms and Average Case Time Complexity
CMPS1371 Introduction to Computing for Engineers SORTING.
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.
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
Section 8.8 Heapsort.  Merge sort time is O(n log n) but still requires, temporarily, n extra storage locations  Heapsort does not require any additional.
CS 206 Introduction to Computer Science II 04 / 27 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Sorting21 Recursive sorting algorithms Oh no, not again!
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
CS 206 Introduction to Computer Science II 12 / 05 / 2008 Instructor: Michael Eckmann.
CHAPTER 11 Sorting.
CS 206 Introduction to Computer Science II 12 / 03 / 2008 Instructor: Michael Eckmann.
Sorting Chapter 10.
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.
CS 206 Introduction to Computer Science II 10 / 08 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 08 / 2008 Instructor: Michael Eckmann.
(c) , University of Washington
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.
ICS 220 – Data Structures and Algorithms
CSCE 3110 Data Structures & Algorithm Analysis Sorting (I) Reading: Chap.7, Weiss.
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.
1 Joe Meehean.  Problem arrange comparable items in list into sorted order  Most sorting algorithms involve comparing item values  We assume items.
Sorting. 2 contents 3 kinds of sorting methods – Selection, exchange, and insertion O(n 2 ) sorts – VERY inefficient, but OK for ≈ 10 elements – Simple.
CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun.
CS 206 Introduction to Computer Science II 04 / 22 / 2009 Instructor: Michael Eckmann.
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.
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.
Intro To Algorithms Searching and Sorting. Searching A common task for a computer is to find a block of data A common task for a computer is to find a.
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
CS 206 Introduction to Computer Science II 10 / 10 / 2008 Instructor: Michael Eckmann.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Sorting.
Quicksort This is probably the most popular sorting algorithm. It was invented by the English Scientist C.A.R. Hoare It is popular because it works well.
SORTING AND ASYMPTOTIC COMPLEXITY Lecture 13 CS2110 – Fall 2009.
CSE 250 – Data Structures. Today’s Goals  First review the easy, simple sorting algorithms  Compare while inserting value into place in the vector 
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Searching and Sorting Searching algorithms with simple arrays
Prof. U V THETE Dept. of Computer Science YMA
Fundamental Data Structures and Algorithms
Programming Abstractions
CSCI 104 Sorting Algorithms
Warmup What is an abstract class?
Lesson Objectives Aims Understand the following “standard algorithms”:
Sorting Chapter 13 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Quicksort and Mergesort
Selection Sort Sorted Unsorted Swap
Unit-2 Divide and Conquer
Ch 7: Quicksort Ming-Te Chi
Sub-Quadratic Sorting Algorithms
CSE 326: Data Structures Sorting
CSE 373 Data Structures and Algorithms
CSC 143 Java Sorting.
Chapter 10 Sorting Algorithms
Searching/Sorting/Searching
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Programming Abstractions in C++, Section 10.2
Presentation transcript:

Programming Abstractions Cynthia Lee CS106X

Today’s Topics Sorting! 1.The warm-ups  Selection sort  Insertion sort 2.Let’s use a data structure!  Heapsort 3.Divide & Conquer  Merge Sort (aka Professor Sorting the Midterms Using TAs and SLs Sort)  Quicksort

Selection Sort A classic “My First Sorting Algorithm” sorting algorithm

Selection Sort Compare the best-case and worst- case costs of this algorithm (tight Big-O characterization of each): A. Best case = Worst case B. Best case < Worst case Why? Explain very specifically. void sort(Vector &vec) { int n = vec.size(); // already-fully-sorted section grows // 1 at a time from left to right for (int lh = 0; lh < n; lh++) { int rh = lh; // find the min element in the // entire unsorted section for (int i = lh + 1; i < n; i++) { // found new min? if (vec[i] < vec[rh]) rh = i; } // swap min into sorted section int tmp = vec[lh]; vec[lh] = vec[rh]; vec[rh] = tmp; }

Bubble Sort It’s not very good, famously so… (arguably better than Selection Sort though!) 5

Insertion Sort Another classic “Beginner” sorting algorithm

Insertion Sort Compare the best-case and worst- case costs of this algorithm (tight Big-O characterization of each): A. Best case = Worst case B. Best case < Worst case Why? Explain very specifically. void sort(Vector & vec) { int n = vec.size(); // already-sorted section grows 1 at a // time from left to right for (int i = 1; i < n; i++) { int j = i; // does this item needs to move // left to be in order? while (j > 0 && vec[j-1] > vec[j]) { // keep swapping this item with // its left neighbor if it is // smaller than the left neighbor int tmp = vec[i]; vec[i] = vec[j]; vec[j] = tmp; j--; }

Heap Sort

Heapsort Pretty simple!! 1.Take the unsorted array and insert each element into a heap priority queue 2.While the queue is not empty, dequeue an element from the heap priority queue The elements come out of the priority queue in sorted order. Fun fact: you don’t need extra array storage, you can do this in place in the original array. 9

Professor’s Sorting Algorithm Sorting in the “real world”

Preliminary Step: We need a “combine two sorted piles” algorithm Start: you have two piles, each of which is sorted  Take the overall smallest element (smallest in either pile) and add that one element to the combined-sorted pile  Repeat until the two starting piles are empty and the combined-sorted pile is complete  Towards the end, you might end up with one pile already empty and the other not, so just move from non-empty pile into combined-sorted pile

Preliminary Step: We need a “combine two sorted piles” algorithm Start: you have two piles, each of which is sorted  Take the overall smallest element (smallest in either pile) and add that one element to the combined-sorted pile  Repeat until the two starting piles are empty and the combined-sorted pile is complete  Towards the end, you might end up with one pile already empty and the other not, so just move from non-empty pile into combined-sorted pile How many elements do we examine to find the overall smallest element?

How many steps does it take to merge two sorted sub- piles, A and B? In other words, how long does it take to do the “combine two sorted piles” algorithm on piles A and B? (best/tight answer) A.O(log(|A|+|B|)) steps B.O(|A|+|B|) steps C.O(|A+B|) 2 steps D.O(|A| 2 + |B| 2 )steps E.Other/none/more than one

Professor’s sorting algorithm: Stanford CS classes can have more than 500 students! Sorting the midterms alphabetically to prepare for handing them back is a non- trivial task. Luckily, I don’t have to do it myself… 1.Find two grad students, give each half of the unsorted midterms 2.Tell the grad students to sort their own pile, then give it back 3.Combine the two piles into one sorted pile, using our simple combine algorithm 4.Done!

Grad student’s sorting algorithm: Sorting ~250 exams is still a non-trivial task! Luckily, the grad students don’t have to do it themselves! 1.Find two SLs, give each half of the unsorted midterms 2.Tell the SLs to sort their own pile, then give it back to you 3.Combine the two piles into one sorted pile, using our simple combine algorithm 4.Done! (give your sorted pile to professor)

SL’s sorting algorithm: 1.Find two students, give each half of the unsorted midterms 2.Tell the students to sort their own pile, then give it back to you 3.Combine the two piles into one sorted pile, using our simple combine algorithm 4.Done! (give sorted pile to grad student)

Student’s sorting algorithm: 1.Find two visiting prospective freshmen (“profros”), give each half of the unsorted midterms 2.Tell the profros to sort their own pile, then give it back to you 3.Combine the two piles into one sorted pile, using our simple combine algorithm 4.Done! (give sorted pile to SL)

ProFro’s sorting algorithm: 1.By now, the pile only has zero or one exam in it (for the sake of this example, assume the starting number of exams makes this true at this point) 2.Done! (give sorted pile to student)

Consider an arbitrarily chosen (generic) particular exam and mentally track its progress throughout the algorithm. How many times does your exam pass through the merge algorithm? A.1 time B.2 times C.Θ(logn) times D.Θ(n) times E.Other/none/more than one (Recall Θ means the same as O but where the time is a best match, not a potentially distant upper bound.)

BigO Analysis of Mergesort Every paper is merged log(n) times  This is the number of times we can divide the stack of n papers by 2 before we can’t divide anymore There are n papers O(nlogn)

Merge Sort runtime intuition Merge sort performs O(N) operations on each level. (width)  Each level splits the data in 2, so there are log 2 N levels. (height)  Product of these = N * log 2 N = O(N log N). (area)  Example: N = 32. Performs ~ log 2 32 = 5 levels of N operations each: width = N height = log 2 N

Merge Sort  Compare the best case and worst case of Merge sort (tight Big-O of each): A. Best case = Worst case B. Best case < Worst case Why? Explain very specifically in terms of the structure of the code.

Quicksort

Divide & Conquer Imagine we want students to line up in alphabetical order to pick up their midterms, which (as we know from Professor sorting algorithm!) are sorted in alphabetical order. 1.“Everybody in the first half of the alphabet, go over there!” “Everybody in the second half, go over there!” › At this point, we at least have some kind of division based on ordering, but it’s very crude. Each of the two “over there” groups is completely unsorted within the group, but... 2.…at least now you have two groups that are each smaller and easier to sort, so recursively sort each half. That’s it!* * ok, actually there are some details…

Divide & Conquer Imagine we want students to line up in alphabetical order to pick up their midterms, which (as we know from Professor sorting algorithm!) are sorted in alphabetical order. 1.“Everybody in the first half of the alphabet, go over there!” “Everybody in the second half, go over there!” › At this point, we at least have some kind of division based on ordering, but it’s very crude. Each of the two “over there” groups is completely unsorted within the group, but... 2.…at least now you have two groups that are each smaller and easier to sort, so recursively sort each half. That’s it!* * ok, actually there are some details… Rather than doing the work of finding the actual median, we just choose an arbitrary or random element to be the divider. Say, the first array index of the group, or randomly select an array index from the group.

Quicksort  Consider the best case and worst case of Quicksort (best/tight characterization in each case) A. Best case = Worst case B. Best case < Worst case Why? Explain very specifically in terms of the structure of the code.