 MergeSort is a sorting algorithm which is more on the advanced end.  It is very fast, but unfortunately uses up a lot of memory due to the recursions.

Slides:



Advertisements
Similar presentations
Back to Sorting – More efficient sorting algorithms.
Advertisements

Garfield AP Computer Science
HST 952 Computing for Biomedical Scientists Lecture 9.
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
Sorting Algorithms n 2 Sorts ◦Selection Sort ◦Insertion Sort ◦Bubble Sort Better Sorts ◦Merge Sort ◦Quick Sort ◦Radix Sort.
CMPS1371 Introduction to Computing for Engineers SORTING.
ADSA: Sorting/ Advanced Data Structures and Algorithms Objective –examine popular sorting algorithms, with an emphasis on divide and conquer.
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.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
1 Sorting. 2 Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort a list,
Merge sort csc326 information structures Spring 2009.
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.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
MergeSort Source: Gibbs & Tamassia. 2 MergeSort MergeSort is a divide and conquer method of sorting.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
ALGORITHM ANALYSIS AND DESIGN INTRODUCTION TO ALGORITHMS CS 413 Divide and Conquer Algortihms: Binary search, merge sort.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
10/14/ Algorithms1 Algorithms - Ch2 - Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
C# PROGRAMMING Searching & Sorting. Objective/Essential Standard Essential Standard 3.00 Apply Advanced Properties of Arrays Indicator 3.03 Apply procedures.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Heapsort. Heapsort is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines.
CSC 211 Data Structures Lecture 13
CSE 341 Lecture 4 merge sort; basic efficiency issues Ullman slides created by Marty Stepp
Sorting 2 Taking an arbitrary permutation of n items and rearranging them into total order Sorting is, without doubt, the most fundamental algorithmic.
Sort Algorithms.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
CHAPTER 6 SORTING ALGORITHMS. Sorting Definition: sorting is the process of sequencing or arranging a list of data items – According to some order – Ascending/descending.
Sorting CS Sorting means... Sorting rearranges the elements into either ascending or descending order within the array. (we’ll use ascending order.)
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2.Solve smaller instances.
Big-O and Sorting February 6, Administrative Stuff Readings for today: Ch Readings for tomorrow: Ch 8.
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.
Contest Algorithms January 2016 Pseudo-code for divide and conquer, and three examples (binary exponentiation, binary search, and mergesort). 5. Divide.
Sorting – Part II CS 367 – Introduction to Data Structures.
1 CSC 211 Data Structures Lecture 18 Dr. Iftikhar Azim Niaz 1.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
CSCI-256 Data Structures & Algorithm Analysis Lecture Note: Some slides by Kevin Wayne. Copyright © 2005 Pearson-Addison Wesley. All rights reserved. 11.
Merge Sort. In plain English: if the size of the array > 1, split the array into two halves, and recursively sort both halves; when the sorts return,
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
Today’s Material Sorting: Definitions Basic Sorting Algorithms
Merge Sort Presentation By: Justin Corpron. In the Beginning… John von Neumann ( ) Stored program Developed merge sort for EDVAC in 1945.
Data Structures Arrays and Lists Part 2 More List Operations.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 8b. Sorting(2): (n log n) Algorithms.
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.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 Algorithms Searching and Sorting Algorithm Efficiency.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 23 Sorting.
Outline This topic covers merge sort
Fundamentals of Algorithms MCS - 2 Lecture # 11
Recitation 13 Searching and Sorting.
MergeSort Source: Gibbs & Tamassia.
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Binary Search Back in the days when phone numbers weren’t stored in cell phones, you might have actually had to look them up in a phonebook. How did you.
Merge sort merge sort: Repeatedly divides the data in half, sorts each half, and combines the sorted halves into a sorted whole. The algorithm: Divide.
Hassan Khosravi / Geoffrey Tien
CS Two Basic Sorting Algorithms Review Exchange Sorting Merge Sorting
Linked List and Selection Sort
Merge sort merge sort: Repeatedly divides the data in half, sorts each half, and combines the sorted halves into a sorted whole. The algorithm: Divide.
Presentation transcript:

 MergeSort is a sorting algorithm which is more on the advanced end.  It is very fast, but unfortunately uses up a lot of memory due to the recursions.  It works by recursively splitting the array into two parts ( ◦ at the midpoint if the number of elements is even, otherwise the right half has one extra ◦ recursing onto each of the two halves. Afterwards, the two halves are merged together

 Here is a visual example of how MergeSort recursively splits the array in half for sorting. I'm using a diagram of a binary tree to represent the steps in our recursion process. Once the array is recursively split into single elements (3, 5, 4, 9, and 2 above), according to the recursive definition we know that those elements are in a sorted order, right?

An array {3} is sorted, because it has only one element. When the recursion is rolling backwards (after expanding), it merges the two branched columns together. Here's a graphical example of how the last merge works (merging [3][5] with [2][4][9]): The first comparison is made:

You may be wondering why it's [2][4][9] and not [4][9][2]. It's [2][4][9], because the array we're merging is already sorted as it was merged the same way in all of the recursions below the current one (below, like in the tree). It appears that 2 is less than 3, so 2 becomes the first element in our array and is removed from the sub-array. The second comparison is made:

 The merging continues as explained while both arrays have elements.  As soon as one of the arrays becomes empty, all the elements of the other array are blindly (without any comparisons) appended onto our final array.  Those elements are already in ascending (sorted) order and are higher than all of the elements presently in the final array.  By 'final array', I'm referring to the array we're building while merging the two sub-arrays together... it is the array that our MergeSort method returns.

 merge sort works as follows: ◦ Divide the unsorted list into two sublists of about half the size ◦ Sort each of the two sublists ◦ Merge the two sorted sublists back into one sorted list.  The algorithm was invented by John von Neumann in 1945.

 public int[] mergeSort(int array[])  // pre: array is full, all elements are valid integers (not null)  // post: array is sorted in ascending order (lowest to highest)  {  // if the array has more than 1 element, we need to split it and merge the sorted halves  if(array.length > 1)  {  // number of elements in sub-array 1  // if odd, sub-array 1 has the smaller half of the elements e.g. if 7 elements total, sub-array 1 will have 3, and sub-array 2 will have 4  int elementsInA1 = array.length/2;  // since we want an even split, we initialize the length of sub-array 2 to equal the length of sub-array 1  int elementsInA2 = elementsInA1;  // if the array has an odd number of elements, let the second half take the extra one  if((array.length % 2) == 1)  elementsInA2 += 1;  // declare and initialize the two arrays once we've determined their sizes  int arr1[] = new int[elementsInA1];  int arr2[] = new int[elementsInA2];  // copy the first part of 'array' into 'arr1', causing arr1 to become full  for(int i = 0; i < elementsInA1; i++)  arr1[i] = array[i];  // copy the remaining elements of 'array' into 'arr2', causing arr2 to become full  for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++)  arr2[i - elementsInA1] = array[i];  // recursively call mergeSort on each of the two sub-arrays that we've just created  // note: when mergeSort returns, arr1 and arr2 will both be sorted!  // it's not magic, the merging is done below, that's how mergesort works :)  arr1 = mergeSort(arr1);  arr2 = mergeSort(arr2);   //the three variables below are indexes that we'll need for merging [i] stores the index of the main array.  // know where to place the smallest element from the two sub-arrays. [j] stores the index of which element from arr1 currently being  //compared [k] stores the index of which element from arr2 is currently being compared  int i = 0, j = 0, k = 0; 

 // the below loop will run until one of the sub-arrays becomes empty  // it means until the index equals the length of the sub-array  while(arr1.length != j && arr2.length != k)  {  // if the current element of arr1 is less than current element of arr2  if(arr1[j] < arr2[k])  {  // copy the current element of arr1 into the final array  array[i] = arr1[j];  // increase the index of the final array to avoid replacing the element which we've just added  i++;  // increase the index of arr1 to avoid comparing the element which we've just added  j++;  }  // if the current element of arr2 is less than current element of arr1  else  {  // copy the current element of arr1 into the final array  array[i] = arr2[k];  // increase the index of the final array to avoid replacing the element which we've just added  i++;  // increase the index of arr2 to avoid comparing the element which we've just added  k++;  }  // at this point, one of the sub-arrays has been exhausted and there are no more elements in it to compare. this means that all the elements in the remaining array are the highest (and sorted), so it's safe to copy them all into thefinal array.  while(arr1.length != j)  {  array[i] = arr1[j];  i++;  j++;  }  while(arr2.length != k)  {  array[i] = arr2[k];  i++;  k++;  }  // return the sorted array to the caller of the function  return array;

 public int[] mergeSort(int array[])  {  if(array.length > 1) {  int elementsInA1 = array.length/2;  int elementsInA2 = elementsInA1;  if((array.length % 2) == 1)  elementsInA2 += 1;  int arr1[] = new int[elementsInA1];  int arr2[] = new int[elementsInA2];  for(int i = 0; i < elementsInA1; i++)  arr1[i] = array[i];  for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++)  arr2[i - elementsInA1] = array[i];  arr1 = mergeSort(arr1);  arr2 = mergeSort(arr2);  int i = 0, j = 0, k = 0; while(arr1.length != j && arr2.length != k) {  if(arr1[j] < arr2[k]) {  array[i] = arr1[j];  i++;  j++; }  else {  array[i] = arr2[k];  i++;  k++; } } //end while  while(arr1.length != j) {  array[i] = arr1[j];  i++;  j++; }  while(arr2.length != k){  array[i] = arr2[k];  i++;  k++; } }  return array;

 1) Use Mergesort to sort numbers.txt and names.txt  2) Modify the code to add a name or number, and sort.