CPS 100 10.1 Sorting: From Theory to Practice l Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm analysis.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Math 130 Introduction to Computing Sorting Lecture # 17 10/11/04 B Smith: Save until Week 15? B Smith: Save until Week 15? B Smith: Skipped Spring 2005?
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
CSCE 3110 Data Structures & Algorithm Analysis
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
25 May Quick Sort (11.2) CSE 2011 Winter 2011.
Data Structures and Algorithms PLSD210 Sorting. Card players all know how to sort … First card is already sorted With all the rest, ¶Scan back from the.
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.
Quicksort Divide-and-Conquer. Quicksort Algorithm Given an array S of n elements (e.g., integers): If array only contains one element, return it. Else.
Sorting Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Quicksort.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
CPS 100, Fall Sorting: From Theory to Practice l Why do we study sorting?  Elegant, practical, powerful, simple, complex  Everyone is doing.
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.
CS 1704 Introduction to Data Structures and Software Engineering.
Sorting HKOI Training Team (Advanced)
A Computer Science Tapestry 11.1 From practice to theory and back again In theory there is no difference between theory and practice, but not in practice.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
CPS 100, Fall Sorting: From Theory to Practice l Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm.
CompSci 100 Prog Design and Analysis II December 2, 2010 Prof. Rodger CompSci 100, Fall
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
CompSci 100e 11.1 Sorting: From Theory to Practice l Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
1 Joe Meehean.  Problem arrange comparable items in list into sorted order  Most sorting algorithms involve comparing item values  We assume items.
CompSci 100e Program Design and Analysis II April 26, 2011 Prof. Rodger CompSci 100e, Spring20111.
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.
1 Sorting Algorithms Sections 7.1 to Comparison-Based Sorting Input – 2,3,1,15,11,23,1 Output – 1,1,2,3,11,15,23 Class ‘Animals’ – Sort Objects.
Searching and Sorting Recursion, Merge-sort, Divide & Conquer, Bucket sort, Radix sort Lecture 5.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Quicksort CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
CompSci 100e 11.1 Sorting: From Theory to Practice l Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm.
Merge Sort. Stable vs. Non-Stable Sorts We frequently use sorting methods for items with multiple keys Sometimes we need to apply the sorting with different.
1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7.
CompSci 100E 30.1 Other N log N Sorts  Binary Tree Sort  Basic Recipe o Insert into binary search tree (BST) o Do Inorder Traversal  Complexity o Create:
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
CompSci Sorting: From Theory to Practice  Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm.
A Computer Science Tapestry 10.1 From practice to theory and back again In theory there is no difference between theory and practice, but not in practice.
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.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
The Sorting Methods Lecture Notes 10. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. –
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Compsci 06/101, Fall Programming Equations l Algorithms + Data Structures = Programs  Niklaus Wirth, old view of programming and compsci l How.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
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.
CS 367 Introduction to Data Structures Lecture 11.
Compsci 06/101, Spring Compsci 6/101: Re[gex|cursion] l Regular expressions and grammars  Recognizing and validating text based on rules  Generating.
SORTING AND ASYMPTOTIC COMPLEXITY Lecture 13 CS2110 – Fall 2009.
The Linear and Binary Search and more Lecture Notes 9.
Advanced Sorting.
Sorting.
Data Structures and Algorithms
Ch 7: Quicksort Ming-Te Chi
8/04/2009 Many thanks to David Sun for some of the included slides!
From practice to theory and back again
Sub-Quadratic Sorting Algorithms
CSE 326: Data Structures Sorting
CSE 373 Data Structures and Algorithms
New sorting algorithms happen …
Compsci 201 Comparators, Sorting
CSE 332: Sorting II Spring 2016.
Sorting: From Theory to Practice
Presentation transcript:

CPS Sorting: From Theory to Practice l Why do we study sorting?  Because we have to  Because sorting is beautiful  Example of algorithm analysis in a simple, useful setting l There are n sorting algorithms, how many should we study?  O(n), O(log n), …  Why do we study more than one algorithm? Some are good, some are bad, some are very, very sad Paradigms of trade-offs and algorithmic design  Which sorting algorithm is best?  Which sort should you call from code you write?

CPS Sorting out sorts (see also sortall.cpp) l Simple, O(n 2 ) sorts --- for sorting n elements  Selection sort --- n 2 comparisons, n swaps, easy to code  Insertion sort --- n 2 comparisons, n 2 moves, stable, fast  Bubble sort --- n 2 everything, slow, slower, and ugly l Divide and conquer faster sorts: O(n log n) for n elements  Quick sort: fast in practice, O(n 2 ) worst case  Merge sort: good worst case, great for linked lists, uses extra storage for vectors/arrays l Other sorts:  Heap sort, basically priority queue sorting  Radix sort: doesn’t compare keys, uses digits/characters  Shell sort: quasi-insertion, fast in practice, non-recursive

CPS Selection sort: summary l Simple to code n 2 sort: n 2 comparisons, n swaps void selectSort(tvector & a) { for(int k=0; k < a.size(); k++){ int minIndex = findMin(a,k,a.size()); swap(a[k],a[minIndex]); } l # comparisons:  Swaps?  Invariant:  k=1 n k = … + n = n(n+1)/2 = O(n 2 ) Sorted, won’t move final position ?????

CPS Insertion Sort: summary l Stable sort, O(n 2 ), good on nearly sorted vectors  Stable sorts maintain order of equal keys  Good for sorting on two criteria: name, then age void insertSort(tvector & a) { int k, loc; string elt; for(k=1; k < a.size(); k++) { elt = a[k]; loc = k; // shift until spot for elt is found while (0 < loc && elt < a[loc-1] { a[loc] = a[loc-1]; // shift right loc=loc-1; } a[loc] = elt; } Sorted relative to each other ?????

CPS Bubble sort: summary of a dog l For completeness you should know about this sort  Few, if any, redeeming features. Really slow, really, really  Can code to recognize already sorted vector (see insertion) Not worth it for bubble sort, much slower than insertion void bubbleSort(tvector & a) { for(int j=a.size()-1; j >= 0; j--) { for(int k=0; k < j; k++) { if (a[k] > a[k+1]) swap(a[k],a[k+1]); } l “bubble” elements down the vector/array Sorted, in final position ?????

CPS Summary of simple sorts l Selection sort has n swaps, good for “heavy” data  moving objects with lots of state, e.g., … A string isn’t heavy, why? (pointer and pointee) What happens in Java? Wrap heavy items in “smart pointer proxy” l Insertion sort is good on nearly sorted data, it’s stable, it’s fast  Also foundation for Shell sort, very fast non-recursive  More complicated to code, but relatively simple, and fast l Bubble sort is a travesty  Can be parallelized, but on one machine don’t go near it (see quotes at end of slides)

CPS Quicksort: fast in practice l Invented in 1962 by C.A.R. Hoare, didn’t understand recursion  Worst case is O(n 2 ), but avoidable in nearly all cases  In 1997 Introsort published (Musser, introspective sort) Like quicksort in practice, but recognizes when it will be bad and changes to heapsort void quick(tvector & a, int left, int right) { if (left < right) { int pivot = partition(a,left,right); quick(a,left,pivot-1); quick(a,pivot+1, right); } l Recurrence? <= X > XX pivot index

CPS Partition code for quicksort left l Easy to develop partition int partition(tvector & a, int left, int right) { string pivot = a[left]; int k, pIndex = left; for(k=left+1, k <= right; k++) { if (a[k] <= pivot){ pIndex++; swap(a[k],a[pIndex]); } swap(a[left], a[pIndex]); } l loop invariant:  statement true each time loop test is evaluated, used to verify correctness of loop l Can swap into a[left] before loop  Nearly sorted data still ok ?????????????? <=>??? <= pivot> pivot pIndex left right leftright what we want what we have invariant pIndex k

CPS Analysis of Quicksort l Average case and worst case analysis  Recurrence for worst case: T(n) =  What about average? l Reason informally:  Two calls vector size n/2  Four calls vector size n/4  … How many calls? Work done on each call? l Partition: typically find middle of left, middle, right, swap, go  Avoid bad performance on nearly sorted data l In practice: remove some (all?) recursion, avoid lots of “clones” T(n-1) + T(1) + O(n) T(n) = 2T(n/2) + O(n)

CPS Tail recursion elimination l If the last statement is a recursive call, recursion can be replaced with iteration  Call cannot be part of an expression  Some compilers do this automatically void foo(int n) void foo2(int n) { if (0 < n) { while (0 < n) { cout << n << endl; cout << n << endl; foo(n-1); n = n-1; } } } l What if cout << and recursive call switched? What about recursive factorial? return n*factorial(n-1);

CPS Merge sort: worst case O(n log n) l Divide and conquer --- recursive sort  Divide list/vector into two halves Sort each half Merge sorted halves together  What is complexity of merging two sorted lists?  What is recurrence relation for merge sort as described? T(n) = l What is advantage of vector over linked-list for merge sort?  What about merging, advantage of linked list?  Vector requires auxiliary storage (or very fancy coding) T(n) = 2T(n/2) + O(n)

CPS Merge sort: lists or vectors l Mergesort for vectors void mergesort(tvector & a, int left, int right) { if (left < right) { int mid = (right+left)/2; mergesort(a, left, mid); mergesort(a, mid+1, right); merge(a,left,mid,right); } l What’s different when linked lists used?  Do differences affect complexity? Why? l How does merge work?

CPS Mergesort continued l Vector code for merge isn’t pretty, but it’s not hard  Mergesort itself is elegant void merge(tvector & a, int left, int middle, int right) // pre: left <= middle <= right, // a[left] <= … <= a[middle], // a[middle+1] <= … <= a[right] // post: a[left] <= … <= a[right] l Why is this prototype potentially simpler for linked lists?  What will prototype be? What is complexity?

CPS Summary of O(n log n) sorts l Quicksort is relatively straight-forward to code, very fast  Worst case is very unlikely, but possible, therefore …  But, if lots of elements are equal, performance will be bad One million integers from range 0 to 10,000 How can we change partition to handle this? l Merge sort is stable, it’s fast, good for linked lists, harder to code?  Worst case performance is O(n log n), compare quicksort  Extra storage for array/vector l Heapsort, more complex to code, good worst case, not stable  Basically heap-based priority queue in a vector

CPS Sorting in practice, see libsort.cpp l Rarely will you need to roll your own sort, but when you do …  What are key issues? l If you use a library sort, you need to understand the interface  In C++ we have STL and sortall.cpp in Tapestry STL has sort, and stable_sort Tapestry has lots of sorts, Mergesort is fast in practice, stable, safe  In C the generic sort is complex to use because arrays are ugly See libsort.cpp  In Java guarantees and worst-case are important Why won’t quicksort be used? l Function objects permit sorting criteria to change simply

CPS Standard sorts: know your library l Know how to use the STL sorts even if you don't use STL  The sort function takes iterators as parameters  vectors, strings and other containers: "give me iterators" What about linked-list iterators? Why aren't these "sortable"? string s = "…."; sort(s.begin(), s.end()); vector vs; // fill vs with values sort(vs.begin(), vs.end()); l Beware C qsort, vary widely and wildly on different platforms  See qsort on Linux/cygwin compared to g++ on Solaris?

CPS Using STL sorts with tvector l Include the right header files  “tvector.h” for tapestry vectors  for STL sorts l Use STL iterators to get beginning and end of vector tvector vec; vec.push_back(“hello”); vec.push_back(“alligator”); sort(vec.begin(), vec.end()); l Can sort strings this way too, but not sets even though they have begin() and end() in STL, why?  Don’t support random access, not sortable

CPS In practice: templated sort functions l Function templates permit us to write once, use several times for several different types of vector  Template function “stamps out” real function  Maintenance is saved, code still large (why?) l What properties must hold for vector elements?  Comparable using < operator  Elements can be assigned to each other l Template functions capture property requirements in code  Part of generic programming  Some languages support this better than others (not Java)

CPS Function object concept l To encapsulate comparison (like operator <) in a parameter  Need convention for parameter : name and behavior  Enforceable by templates or by inheritance (or both) Sorts don’t use inheritance, tpqueue does l Name convention: class/object has a method named compare  Two parameters, the (vector) elements being compared  See comparer.h, used in sortall.h and in tpq.h l Behavior convention: compare returns an int  zero if elements equal  +1 (positive) if first > second  -1 (negative) if first < second

CPS Function object example class StrLenComp // : public Comparer { public: int compare(const string& a, const string& b) const // post: return -1/+1/0 as a.length() < b.length() { if (a.length() < b.length()) return -1; if (a.length() > b.length()) return 1; return 0; } }; // to use this: StrLenComp scomp; if (scomp.compare(“hello”, “goodbye”) < 0) …  We can use this to sort, see sortall.h  Call of sort: InsertSort(vec, vec.size(), scomp);

CPS Non-comparison-based sorts lower bound:  (n log n) for comparison based sorts (like searching lower bound) l bucket sort/radix sort are not- comparison based, faster asymptotically and in practice l sort a vector of ints, all ints in the range , how?  (use extra storage) l radix: examine each digit of numbers being sorted  One-pass per digit  Sort based on digit

CPS Shell sort l Comparison-based, similar to insertion sort  Using Hibbard’s increments (see sortall.h) yields O(n 3/2 )  Sequence of insertion sorts, note last value of h!! int k,loc,h; string elt; h = …; // set h to 2 p -1, just less than a.size() while (h > 0) { for(k=h; k < n; k++) { elt=a[k]; loc = k; while (h <= loc && elt < a[loc-h]) { a[loc] = a[loc-h]; loc -= h; } a[loc] = elt; } h /= 2; }

CPS Jim Gray (Turing 1998) l Bubble sort is a good argument for analyzing algorithm performance. It is a perfectly correct algorithm. But it's performance is among the worst imaginable. So, it crisply shows the difference between correct algorithms and good algorithms. (italics ola’s)

CPS Brian Reid (Hopper Award 1982) Feah. I love bubble sort, and I grow weary of people who have nothing better to do than to preach about it. Universities are good places to keep such people, so that they don't scare the general public. ( continued )

CPS Brian Reid (Hopper 1982) I am quite capable of squaring N with or without a calculator, and I know how long my sorts will bubble. I can type every form of bubble sort into a text editor from memory. If I am writing some quick code and I need a sort quick, as opposed to a quick sort, I just type in the bubble sort as if it were a statement. I'm done with it before I could look up the data type of the third argument to the quicksort library. I have a dual-processor 1.2 GHz Powermac and it sneers at your N squared for most interesting values of N. And my source code is smaller than yours. Brian Reid who keeps all of his bubbles sorted anyhow. Good paper, by the way. Well written and actually has something to say.

CPS Niklaus Wirth (Turing award 1984) I have read your article and share your view that Bubble Sort has hardly any merits. I think that it is so often mentioned, because it illustrates quite well the principle of sorting by exchanging. I think BS is popular, because it fits well into a systematic development of sorting algorithms. But it plays no role in actual applications. Quite in contrast to C, also without merit (and its derivative Java), among programming codes.

CPS Guy L. Steele, Jr. (Hopper ’88) (Thank you for your fascinating paper and inquiry. Here are some off-the-cuff thoughts on the subject. ) I think that one reason for the popularity of Bubble Sort is that it is easy to see why it works, and the idea is simple enough that one can carry it around in one's head … continued

CPS Guy L. Steele, Jr. As for its status today, it may be an example of that phenomenon whereby the first widely popular version of something becomes frozen as a common term or cultural icon. Even in the 1990s, a comic-strip bathtub very likely sits off the floor on claw feet. … it is the first thing that leaps to mind, the thing that is easy to recognize, the thing that is easy to doodle on a napkin, when one thinks generically or popularly about sort routines.