IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Sorting Chapter 8 CSCI 3333 Data Structures.
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
CSE 373: Data Structures and Algorithms
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
1 Today’s Material Divide & Conquer (Recursive) Sorting Algorithms –QuickSort External Sorting.
QuickSort The content for these slides was originally created by Gerard Harrison. Ported to C# by Mike Panitz.
Sorting Algorithms and Average Case Time Complexity
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.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
CSE 373: Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
Spring 2010CS 2251 Sorting Chapter 8. Spring 2010CS 2252 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn.
Quicksort. 2 Introduction * Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case: O(N 2 ) n But, the worst case seldom.
Sorting Chapter 10.
Quicksort.
Sorting Algorithms Bubble Sort Merge Sort Quick Sort Randomized Quick Sort.
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.
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.
1 Algorithmic analysis Introduction. This handout tells you what you are responsible for concerning the analysis of algorithms You are responsible for:
CS2420: Lecture 11 Vladimir Kulyukin Computer Science Department Utah State University.
CSE 373 Data Structures Lecture 19
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
(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.
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.
Computer Science Searching & 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.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
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.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Comparison-Based Sorting & Analysis Smt Genap
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
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 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
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.
Sorting: Advanced Techniques Smt Genap
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 Sorting اعداد: ابوزيد ابراهيم حامد سعد صبرة حميده الشاذلي عبدالاه السيد محمد احمد.
SORTING ALGORITHMS King Saud University College of Applied studies and Community Service CSC 1101 By: Nada Alhirabi 1.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
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)
Today’s Material Sorting: Definitions Basic Sorting Algorithms
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Data Structures and Algorithms Instructor: Tesfaye Guta [M.Sc.] Haramaya University.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Prof. U V THETE Dept. of Computer Science YMA
Sorting Mr. Jacobs.
CSC215 Lecture Algorithms.
Discrete Mathematics CMP-101 Lecture 12 Sorting, Bubble Sort, Insertion Sort, Greedy Algorithms Abdul Hameed
Sub-Quadratic Sorting Algorithms
slides adapted from Marty Stepp
slides created by Marty Stepp
CSE 373: Data Structures and Algorithms
CSE 373 Data Structures and Algorithms
Advanced Sorting Methods: Shellsort
Presentation transcript:

IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Sorting algorithms & their analysis

2 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Several sorting algorithms: Bubble Sort Selection Sort Insertion Sort Shell Sort Merge Sort Quick Sort For each algorithm: Basic Idea Example Implementation Algorithm Analysis Outline

3 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Sorting Sorting = ordering. Sorted = ordered based on a particular way. Generally, collections of data are presented in a sorted manner. Examples of Sorting: Words in a dictionary are sorted (and case distinctions are ignored). Files in a directory are often listed in sorted order. The index of a book is sorted (and case distinctions are ignored). Many banks provide statements that list checks in increasing order (by check number). In a newspaper, the calendar of events in a schedule is generally sorted by date. Musical compact disks in a record store are generally sorted by recording artist. Why? Imagine finding the phone number of your friend in your mobile phone, but the phone book is not sorted.

4 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Bubble Sort: Idea Idea: bubble in water. Bubble in water moves upward. Why? How? When a bubble moves upward, the water from above will move downward to fill in the space left by the bubble. As a sorting algo: During each iteration, compare adjacent items: the “bubble” floats, the “water” sinks! (i.e. swap items)

5 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Bubble sort: an iteration

6 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Bubble Sort: Example Notice that at least one element will be in the correct position each iteration.

7 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Bubble Sort: Example Stop here… why?

8 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Bubble Sort: Implementation void sort(int a[]){ for (int i = a.length; i>=0; i--) { boolean swapped = false; for (int j = 0; j<i; j++) {... if (a[j] > a[j+1]) { int T = a[j]; a[j] = a[j+1]; a[j+1] = T; swapped = true; }... } if (!swapped) return; }

9 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Bubble Sort: Analysis Running time: Worst case: O(N 2 ) Best case: O(N) -- when? why? Variant: bi-directional bubble sort original bubble sort: only works in one direction bi-directional bubble sort: works back and forth.

10 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Selection Sort: Idea 1. Initial condition: Unsorted list = data Sorted list = empty 2. Select the “best” (e.g. smallest) item from the unsorted group, then add the “best” item at the end of the sorted group. 3. Repeat the process until the unsorted group becomes empty.

11 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Selection Sort: Example

12 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Selection Sort: Example

13 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Selection Sort: Example

14 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Selection Sort: Implementation void sort(int a[]) throws Exception { for (int i = 0; i < a.length; i++) { int min = i; for (int j = i + 1; j < a.length; j++) if (a[j] < a[min]) min = j; int T = a[min]; a[min] = a[i]; a[i] = T; } Select best item from unsorted list. Add it to the end of the sorted list.

15 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Selection Sort: Analysis Running time: Worst case: O(N 2 ) Best case: O(N 2 ) Based on big-oh analysis, is selection sort better than bubble sort? Does the actual running time reflect the analysis?

16 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Insertion Sort: Idea 1. Initial condition: Unsorted list = data Sorted list = empty 2. Take the first (any) item from the unsorted group, then insert it at its correct position in the sorted group. 3. Repeat the process until the unsorted group becomes empty.

17 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Insertion Sort: Idea Imagine you are sorting a hand of cards. 8 | | | | | |

18 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Insertion Sort: Example

19 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Insertion Sort: Example

20 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Insertion Sort: Example

21 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Insertion Sort: Example

22 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Insertion Sort: Implementation public static void insertionSort (int[] a) { for (int ii = 1; ii < a.length; ii++) { int jj = ii; while (( jj > 0) && (a[jj] < a[jj - 1])) { int temp = a[jj]; a[jj] = a[jj - 1]; a[jj - 1] = temp; jj--; } Note that a[jj] is always the same  we can make things a bit more efficient! Get first item in unsorted list. Insert it in the sorted list.

23 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Insertion Sort: Efficient Implementation A slightly more efficient Insertion sort public static void insertionSort2 (int[] a) { for (int ii = 1; ii < a.length; ii++) { int temp = a[ii]; int jj = ii; while (( jj > 0) && (temp < a[jj - 1])) { a[jj] = a[jj - 1]; jj--; } a[jj] = temp; }

24 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Insertion Sort: Analysis Running time analysis: Worst case: O(N 2 ) Best case: O(N) Is insertion sort faster than selection sort? Notice the similarity and the difference between insertion sort and selection sort.

25 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 A Lower Bound Bubble Sort, Selection Sort, Insertion Sort all have worst case of O(N 2 ). It turns out, for any algorithm that exchanges adjacent items, this is the best worst case: Ω (N 2 ) In other words, this is a lower bound! See proof in Section 8.3 of Weiss

26 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Original: 5-sort: Sort items with distance 5 elements: Shell Sort: Idea Donald Shell (1959): Exchange items that are far apart!

27 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Original: After 5-sort: After 3-sort: Shell Sort: Example After 1-sort:

28 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Shell Sort: Gap Values Gap: the distance between items being sorted. As we progress, the gap decreases. Shell Sort is also called Diminishing Gap Sort. Shell proposed starting gap of N/2, halving at each step. There are many ways of choosing the next gap.

29 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 O(N 3/2 )?O(N 5/4 )? O(N 7/6 )? Shell Sort: Analysis So we have 3 nested loops, but Shell Sort is still better than Insertion Sort! Why?

30 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Mergesort: Basic Idea Divide and Conquer approach Idea: Merging two sorted array takes O(n) time Split an array into two takes O(1) time Counter A Counter B Counter c

31 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Mergesort: Merge Implementation Implement operation to merge two sorted arrays into one sorted array: public static void merge(int[] A, int[] B, int[] C) { } Assume A and B are sorted and |C| = |A| + |B|

32 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Mergesort: Algorithm 1. Base case: if the number of items to sort is 0 or 1, return. 2. Recursive case: recursively sort the first and second half separately. 3. Merging step: merge the two sorted halves into a sorted group.

33 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week split Mergesort: Example

34 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week split merge Mergesort: Example

35 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 merge Mergesort: Example

36 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Mergesort: Implementation MergeSort implementation (and ‘driver’ method) void mergeSort(int[] array) {mergeSort(array, 0, a.length-1);} void mergeSort(int[] a, int left, int right) { if(left < right) { int centre = (left + right)/2; mergeSort(a, left, centre); mergeSort(a, center+1, right); merge(a, left, center+1, right); } How to merge the two subarrays of A without any “temporary” space?

37 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Implement operation to merge two sorted subarrays: public static void merge(int[] A, int l, int c, int r) { } Mergesort: Merge Implementation

38 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Mergesort: Analysis Running Time: O(n log n) Why?

39 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Quicksort: Basic Idea Yet another divide and conquer approach quickSort(S) algorithm: If the number of items in S is 0 or 1, return. Pick any element v  S. This element is called the pivot. Partition S – { v } into two disjoint groups: L = { x  S – { v } | x  v } and R = { x  S – { v } | x  v } Return the result of quickSort(L), followed by v, followed by quickSort(R).

40 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Quicksort: Select Pivot

41 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Quicksort: Partition

42 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Quicksort: Recursive Sort & Merge

43 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week left 40 right Quicksort: Partition Algorithm

44 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week leftright Quicksort: Partition Algorithm 1

45 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week Quicksort: Partition Algorithm 1

46 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Quicksort: Partition Algorithm original pivot = 40 while < pivot left++ while >= pivot right rightleft rightleft “move pivot out of the way”

47 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Quicksort: Partition Algorithm rightleft rightleft CROSSING: Quicksort recursively “move pivot back” Quicksort recursively

48 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 static void QuickSort(int a[], int low, int high) { if(high <= low) return; // base case pivot = choosePivot(a); // select “ best ” pivot int i=low, j=high-1; swap(a,pivot,a[j]); // move pivot out of the way while(i <= j) { // find large element starting from left while(i<high && a[i]<pivot) i++; // find small element starting from right while(j>low && a[j]>=pivot) j--; // if the indexes have not crossed, swap if(i>j) swap(a, i, j); } swap(a,i,high-1); // restore pivot quickSort(a,low,i-1); // sort small elements quickSort(a,i+1,high); // sort large elements } Quicksort: Implementation

49 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Quicksort: Analysis Partitioning takes O(n) Merging takes O(1) So, for each recursive call, the algorithm takes O(n) How many recursive calls does a quick sort need?

50 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Quicksort: Choosing The Pivot Ideal pivot: Median element Common pivot First element Element at the middle Median of three

51 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 Epilogue: Generic Sort So far we have methods to sort integers. What about Strings? Employees? Cookies? A new method for each class? No! In order to be sorted, objects should be comparable (less than, equal, greater than). Solution: use an interface that has a method to compare two objects. Remember: A class that implements an interface inherits the interface (method definitions) = interface inheritance, not implementation inheritance.

52 Ruli Manurung (Fasilkom UI)IKI10100I: Data Structures & Algorithms Week 5 The Comparable Interface In Java, generic aspect of “comparable” is defined in an interface in package java.lang : Method compareTo returns: <0: the object ( this ) is smaller than the parameter ‘ ob ’ 0: the object ( this ) is equal to the parameter ‘ ob ’ >0: the object ( this ) is greater than the parameter ‘ ob ’ public interface Comparable { public int compareTo (Object ob); }