CS203 Programming with Data Structures Sorting California State University, Los Angeles.

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

Visual C++ Programming: Concepts and Projects
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
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.
Chapter 7: Sorting Algorithms
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
Sorting Algorithms and Average Case Time Complexity
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.
CS 162 Intro to Programming II Quick Sort 1. Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage.
Sorting Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
Sorting Algorithms Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Sorting. Introduction Assumptions –Sorting an array of integers –Entire sort can be done in main memory Straightforward algorithms are O(N 2 ) More complex.
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
Sorting Chapter 10.
1 7.5 Heapsort Average number of comparison used to heapsort a random permutation of N items is 2N logN - O (N log log N).
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
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.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
CSE 373 Data Structures Lecture 19
Simple Sort Algorithms Selection Sort Bubble Sort Insertion Sort.
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
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.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
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.
Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All.
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
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.
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.
Sorting Sorting: –Task of rearranging data in an order. –Order can be: Ascending Order: –1,2,3,4,5,6,7,8,9 Descending Order: –9,8,7,6,5,4,3,2,1 Lexicographic.
Sorting CSIT 402 Data Structures II. 2 Sorting (Ascending Order) Input ›an array A of data records ›a key value in each data record ›a comparison function.
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.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7.
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.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
Divide and Conquer Sorting Algorithms COMP s1 Sedgewick Chapters 7 and 8.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Sorting.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
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 Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
CS 367 Introduction to Data Structures Lecture 11.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Sorting and Runtime Complexity CS255. Sorting Different ways to sort: –Bubble –Exchange –Insertion –Merge –Quick –more…
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Lecture 14 Searching and Sorting Richard Gesick.
Chapter 7 Sorting Spring 14
Description Given a linear collection of items x1, x2, x3,….,xn
Lecture 11 Searching and Sorting Richard Gesick.
Sorting … and Insertion Sort.
Sub-Quadratic Sorting Algorithms
CSE 326: Data Structures Sorting
EE 312 Software Design and Implementation I
CSE 373 Data Structures and Algorithms
Searching/Sorting/Searching
Workshop for CS-AP Teachers
Presentation transcript:

CS203 Programming with Data Structures Sorting California State University, Los Angeles

Sorting Given an collection of elements, rearrange the elements so that they are in ascending or descending order The collection is usually an array The elements are comparable For example: Before sorting: After sorting:

Bubble Sort Or in other words Find the smallest element and put it at 1 st position Find the second smallest element and put it ant 2 nd position … Given an array of size N For i=0 to N-1 find the smallest element in the range i+1 to N-1, and swap it with the element at position i Done

Bubble Sort Example First iteration: i=0 The smallest element in the rang 1 to 5 is 10 Swap 10 and After 1 st iteration:

Comparison and Swap Bubble sort Number of comparisons?? Number of swaps?? Can we improve on Bubble Sort??

Decision Tree a,b,c a,c,b b,c,a b,a,c c,a,b c,b,a a,b,c a,c,b c,a,b b,a,c b,c,a c,b,a a,b,c a,c,b c,a,b b,a,c b,c,a c,b,a a,b,ca,c,bb,a,cb,c,a a<bb<a a<cc<ab<cc<b b<cc<ba<cc<a

Properties of A Decision Tree Number of leaves: ?? Height of the tree: ??

Insertion Sort Make N-1 passes of the array At pass p, the first p elements of the array are already sorted. “insert” a[p+1] so the first p+1 elements are sorted.

Insertion Sort Example st Pass: sorted unsorted Take 10 and insert it into the sorted portion: After insertion: sorted unsorted

Insertion Sort Implementation Implementation #1: Binary search for insertion position shift elements to the right Insert Complexity of pass P logP comparisons P/2 assignments

Insertion Sort Implementation Implementation #2: Pair-wise swap Complexity of pass P P/2 comparisons P/2 swaps

Heap Sort Heap sort strategy Construct a heap with N insertions Construct a sorted array with N removeMin Can we construct the heap more efficiently (in linear time)?? Can we perform heap sort without the extra space requirement??

Percolate Down

Percolate Down

Percolate Down

percolateDown void percolateDown( int pos ) { int child; Comparable tmp = array[pos]; while( pos*2 <= size ) { child = pos * 2; if( child != size && array[child+1].compareTo(array[child]) < 0 ) child++; if( array[child].compareTo(tmp) < 0 ) array[pos] = array[child]; else break; pos = child; } array[pos] = tmp; }

Building A Heap Percolate down the non-leaf nodes in reverse order

Heap Building Example

Heap Sort Algorithm Build a MaxHeap removeMax() then put the removed value into the last position

Merge Sort Merging two sorted arrays takes linear time

Merge Sort Example

Merge Sort Code … Comparable tmpArray[]; void mergeSort( Comparable a[] ) { tmpArray = new Comparable[a.length]; mergeSort( a, 0, a.length-1 ); }

… Merge Sort Code void mergeSort( Comparable a[], int left, int right ) { if( left < right ) { int mid = (left+right) / 2; mergeSort( a, left, mid ); mergeSort( a, mid+1, right ); merge( a, left, mid, right ); }

About Merge Sort Complexity T(1) = 1 T(N) = 2T(N/2) + N Rarely used in practice Require extra space for the temporary array Copying to and from the temporary array is costly O(NlogN)

Quick Sort Fastest sorting algorithm in practice Complexity Average case: O(NlogN) Worst case: O(N 2 ) Easy to understand, very hard to code correctly

Quick Sort Algorithm 1. If |A|=1 or 0, return 2. Pick any element v in A. v is called the pivot. 3. Partition A-{v} (the remaining elements in A ) into two disjoint groups A 1 and A 2 A 1 = {x  A-{v} | x  v} A 2 = {x  A-{v} | x  v} 4. Return {quicksort( A 1 ), v, quicksort( A 2 )} Given array A

Understand The Notations A: v: A1:A1: A2:A2:

Observations About The Quick Sort Algorithm It should work It’s not very clearly defined How do we pick the pivot? How do we do the partitioning? How do we handle duplicate values? Why is it more efficient than Merge Sort?

Picking the Pivot Ideally, the pivot should leads to two equal-sized partitions First element?? Random pick?? Median of (first, middle, last)

Partitioning … Pivot = median(30,21,10) = 21 A: 1. Swap pivot to the last position ij

… Partitioning 2. Increase i until a[i] > pivot Decrease j until a[j] < pivot swap a[i] and a[j] 3. Repeat 2 until i > j 4. Swap a[i] and pivot We want to move smaller elements to the left part of the array and larger elements to the right part, So:

More Details Handing duplicates Small arrays N>10: quick sort N  10: insertion sort

Exercise Implement quickSort