1 Data Structures CSCI 132, Spring 2014 Lecture 31 Merge Sort Analysis Quick Sort.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
Practice Quiz Question
1 Data Structures CSCI 132, Spring 2014 Lecture 37 Binary Search Trees II.
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Using Divide and Conquer for Sorting
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
Data Structures Data Structures Topic #13. Today’s Agenda Sorting Algorithms: Recursive –mergesort –quicksort As we learn about each sorting algorithm,
Internal Sorting A brief review and some new ideas CS 400/600 – Data Structures.
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
Chapter 8 SORTING. Outline 1. Introduction and Notation 2. Insertion Sort 3. Selection Sort 4. Shell Sort 5. Lower Bounds 6. Divide-and-Conquer Sorting.
Chapter 8: Sorting. Contents Algorithms for Sorting List (both for contiguous lists and linked lists) –Insertion Sort –Selection Sort –Bubble / Quick.
Chapter 19: Searching and Sorting Algorithms
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.
Quick Sort. Quicksort Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare. The quick sort is an in-place, divide- and-conquer, massively.
CS 171: Introduction to Computer Science II Quicksort.
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.
Data Structures Advanced Sorts Part 2: Quicksort Phil Tayco Slide version 1.0 Mar. 22, 2015.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
CHAPTER 11 Sorting.
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 6 Chapter 6 –Insertion Sort 6.1 –Quicksort 6.2 Chapter 5 Chapter 5 –Mergesort 5.2 –Stable Sorts Divide & Conquer.
MergeSort Source: Gibbs & Tamassia. 2 MergeSort MergeSort is a divide and conquer method of sorting.
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
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.
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 8 SORTING 1. Introduction and Notation 2. Insertion Sort 3. Selection Sort 4. Shell Sort 5. Lower Bounds 6. Divide-and-Conquer Sorting.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
1 Lecture 16: Lists and vectors Binary search, Sorting.
Sorting. We live in a world obsessed with keeping information, and to find it, we must keep it in some sensible order. You learned in the last chapter.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
1 Data Structures CSCI 132, Spring 2014 Lecture 30 Comparison trees, Merge Sort.
Lecture10: Sorting II Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Heapsort. Heapsort is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
Data Structures Using C++ 2E Chapter 10 Sorting Algorithms.
CSC 211 Data Structures Lecture 13
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
Sort Algorithms.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Data Structures Using C++1 Chapter 10 Sorting Algorithms.
Sorting – Part II CS 367 – Introduction to Data Structures.
Chapter 9 Sorting 1. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step.
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.
Kruse/Ryba ch081 Object Oriented Data Structures Sorting Insertion Sort Selection Sort Index Sort Shell Sort Divide and Conquer Sort Merge Sort Quick Sort.
CSE 326: Data Structures Lecture 23 Spring Quarter 2001 Sorting, Part 1 David Kaplan
Chapter 4, Part II Sorting Algorithms. 2 Heap Details A heap is a tree structure where for each subtree the value stored at the root is larger than all.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
SORTING AND ASYMPTOTIC COMPLEXITY Lecture 13 CS2110 – Fall 2009.
1 CS 132 Spring 2008 Chapter 10 Sorting Algorithms.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
WHICH SEARCH OR SORT IS BETTER?. COMPARING ALGORITHMS Time efficiency refers to how long it takes an algorithm to run Space efficiency refers to the amount.
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Sorting and Runtime Complexity CS255. Sorting Different ways to sort: –Bubble –Exchange –Insertion –Merge –Quick –more…
Lecture No.45 Data Structures Dr. Sohail Aslam.
Warmup What is an abstract class?
Sorting Algorithms CENG 213 Data Structures 1.
Data Structures Using C++ 2E
Advanced Sorting Methods: Shellsort
Core Assessments Core #1: This Friday (5/4) Core #2: Tuesday, 5/8.
Advanced Sorting Methods: Shellsort
CMPT 225 Lecture 10 – Merge Sort.
Presentation transcript:

1 Data Structures CSCI 132, Spring 2014 Lecture 31 Merge Sort Analysis Quick Sort

2 Merge Sort Divide the list into 2 equal halves. Keep dividing until list length = 1. Merge sublists into sorted list:

3 Implementation of Merge Sort template void Sortable_list :: merge_sort( ) { recursive_merge_sort(head); } template void Sortable_list :: recursive_merge_sort(Node * &sub_list) { if (sub_list != NULL && sub_list->next != NULL) { Node *second_half = divide_from(sub_list); recursive_merge_sort(sub_list); recursive_merge_sort(second_half); sub_list = merge(sub_list, second_half); } }

4 divide_from( ) returns a pointer to the middle of the list position midpointsecond_half sub_list positionmidpoint sub_list To find the midpoint, move the midpoint pointer one step for every two steps moved by the position pointer. Return second_half, which points to the node following the midpoint.

5 divide_from( ) template Node *Sortable_list :: divide_from(Node *sub_list) { Node *position, // traverses the entire list *midpoint, // moves at half speed of position to midpoint *second_half; if ((midpoint = sub_list) == NULL) return NULL; // List is empty. position = midpoint->next; while (position != NULL) { // Move position twice for midpoint’s one move. position = position->next; if (position != NULL) { midpoint = midpoint->next; position = position->next; } } second_half = midpoint->next; midpoint->next = NULL; return second_half; }

6 merge( ) combines two sorted sublists first second first second combined last_sorted Compare values in first node of the two lists. Add whichever is smaller to combined list. Keep track of last_sorted, first and second pointers. Return combined.next

merge( ) template Node *Sortable_list :: merge(Node *first, Node *second) { Node *last_sorted; // points to the last node of sorted list Node combined; // dummy first node, points to merged list last_sorted = &combined; while (first != NULL && second != NULL) { // Attach node with smaller key if (first->entry entry) { last_sorted->next = first; last_sorted = first; first = first->next; // Advance to the next unmerged node. } else { last_sorted->next = second; last_sorted = second; second = second->next; } } if (first == NULL) // After one list ends, attach the remainder of the other. last_sorted->next = second; else last_sorted->next = first; return combined.next; }

8 Recursion Tree for Merge Sort

9 Counting Comparisons for Merge Sort The only function that does comparisons is merge( ). With each comparison, one item is put into the correct position. Therefore, merge does a maximum of n comparisons when merging a total of n items. (In fact, it does a maximum of n-1 comparisons).

10 How many items are merged? Recursion tree for n = 16: Total items merged at each level: 16 0

11 Number of Comparisons In general, for list length n: n items are merged at each level of the recursion tree, requiring at most n comparisons. The number of levels in the recursion tree is lg(n). (Because the tree is a 2-tree with n leaves). Therefore, the number of key comparisons is no greater than n*(number of levels) = n lg(n) Refinement of the count shows that merge sort does n lg(n) *n + 1 comparisons on average. This is close to the theoretical lower bound for number of comparisons done by a sorting algorithm.

12 Quick Sort Merge Sort can be a problem for contiguous lists. It is difficult to merge 2 contiguous sublists efficiently, unless you create a separate array to hold the merged list. But, creating a separate array uses more memory space. Quick Sort avoids this problem by dividing the list into 2 sublists in which all the entries in one are less than some value (pivot) and all the entries in the other are greater than or equal to the pivot.

13 Quick Sort example pivot partition low high partition combine with pivot

14 Implementation of Quick Sort template void Sortable_list :: quick_sort( ) { recursive_quick_sort(0, count - 1); } template void Sortable_list :: recursive_quick_sort(int low, int high) { int pivot_position; if (low < high) { // Otherwise, no sorting is needed. pivot_position = partition(low, high); recursive_quick_sort(low, pivot_position - 1); recursive_quick_sort(pivot_position + 1, high); } }

15 The partition algorithm pivot = pivot x ? lowlast smalli swap if x < pivot pivot = pivot a ? lowlast smalli

16 Implementation of partition template int Sortable_list :: partition(int low, int high){ Record pivot; int i; // used to scan through the list int last_small; // position of the last key less than pivot swap(low, (low + high)/2); pivot = entry[low]; // First entry is now pivot. last_small = low; for (i = low + 1; i <= high; i++) { if (entry[i] < pivot) { last_small = last_small + 1; swap(last_small, i); } } swap(low, last_small); // Put the pivot into its proper position. return last_small; }

17 Running time of Quick Sort Best case: Partition list into 2 equal halves each round. Run time = O(n lg(n) ) Worst case: Partition list into (n-1) list and 0 (pivot not included) Run time= (n-1) + (n-2) = 0.5n n Average case: Run time = 1.4 n lg(n) + O(n)

18 Comparison of Sorting Algorithms Trade off: Use of storage space. Use of computer time. Programming effort. Quick Sort and Merge Sort use more space (because they are recursive functions), but run faster. For contiguous lists, quick sort has better use of space. Insertion sort and Selection sort are relatively slow (O(n 2 )). But, they use less memory space and are somewhat easier to program.