Docsity

Merge Sort Algorithm: Divide and Conquer Approach, Study Guides, Projects, Research of Data Structures and Algorithms

Partial preview of the text

Download Merge Sort Algorithm: Divide and Conquer Approach and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity!

MERGE SORT

Your Date Here Your Footer Here ALGORITHM

OUTLINE HOW MERGE SORT WORKS GENERAL PRINCIPLES USING SAMPLE ARRAY TIME COMPLEXITIES

INTRODUCTION USING CODE SAMPLE

How Merge Sort uses “Divide and Conquer Algorithm: 4 It basically has 3 steps:

  1. Divide: Breaking the problem into subproblems
  2. Conquer: Recursively solving the subproblems
  3. Combine: Combining the solutions to get the final result.

MERGE GENERAL PRINCIPLES SORT Sorting Problem: Sort a sequence of n elements into non-decreasing order. Divide: Split array in half Conquer: Call merge sort on each half to sort them recursively Combine: Merge both halves into one sorted array.

 (^) Worst Case Time Complexity: O(nlog n)* 7 ALGORITHM  (^) Best Case Time Complexity: O(nlog n)*  Average Time Complexity: O(nlog n)*

Your Date Here 8 #include using namespace std; void printArray(int, int); void mergeSort(int, int, int); void merge(int*, int, int, int); int main(){ int arr[] = {9,8,3,5,4}; //define an unsorted array int size = sizeof(arr)/sizeof(arr[0]); //calculate the array length mergeSort(arr, 0, size-1); //call mergeSort on the array, and pass in the leftmost & rightmost indexes printArray(arr, size) ; //print the array return 0; }

//calculate sizes of left and right arrays int size1 = sizeof(arrL)/sizeof(arrL[0]); int size2 = sizeof(arrR)/sizeof(arrR[0]); int dex1, dex2, dex3;//index variables for left, right and merged arrays //copy data to temporary arrays for(dex1=0;dex1<size1;dex1++){ arrL[dex1] = arr[left+dex1]; } for(dex2=0;dex2<size2;dex2++){ arrR[dex2] = arr[mid+1+dex2]; }

M