of 33/33
BY Halima Khan NIazi
• date post

22-Jan-2017
• Category

## Engineering

• view

42

0

Embed Size (px)

### Transcript of Merge sort algorithm

• BYHalima Khan NIazi

• Sorting is a process of arranging data in some logical orderIn case of numeric values order may be ascending or descending or dictionary order(lexicographical order) in case of alphanumeric values.There are two types of sorting

Internal sortingExternal sorting

• Dictionary Phone contacts

• Merge sort is a sorting algorithm that sortsdata items into ascending order whichcomes under the category of comparisonbased sorting .It is a technique based on divide and conquer.Merge sort first divides the array into equal halves and the combine them in a sorted manner.

• Divide.

• combine

• Consider an array having 6 elements

5 4 3 1 2 6Arrange the elements in ascending order using quick sort algorithm

• begendstarting index of the arrayending index of the arrayEnd

012345543126

• begendIs beg
• begendstarting index of the arrayending index of the array

if beg

• begendwe will first consider the left sub arrayLeft sub-arrayRight sub-array

012345543126

• endbegLeft sub-arrayIf beg
• end begIf beg
• 012345543126

012543

0154

03

04

05

04

012126

0112

26

06

02

01

• Conquer and combine Is 5

• Left sub arrayRight sub-array As 4&5 > 3 So merge sorted the left side

0154

03

• Left sub arrayNow we can move to right sub arrayLeft sub arrayRight sub-arrayThe left sub array is sorted

012345543126

012345

• Left sub arrayRight sub-arrayLeft sub arrayRight sub-arrayleft sub array is sorted we can move to right the right sub array

012345543126

012345

000126

• Right sub-array

LeftRightIs 1

• Left sub arrayRight sub arrayThe left sub array is sorted So we can move to right sub array

Left sub arrayRight sub-array

012126

0112

06

012345543126

• Left sub arrayRight sub-arrayAs there is only one element in the right sub array So we can now sort the right sub array with left sorted sub arrayas 1 and 2 are both less than 6 so we dont have to swap position

012345543126

012126

0112

06

• Left sub arrayRight sub-arrayLeft sub arrayRight sub-arrayAs both the left and right sub array are sortedwe just have to merge them in ascending order using merging algorithm

012345543126

012345

012126

012345543126

• Is 3
• Is 3
• Is 3
• Is 4
• Is 5
• 012345143126

• #include#includevoid merge_sort(int *,int,int);void merge(int *,int,int,int);int main(){ int array[30],n,i; cout
• merge_sort(array,0,n-1); cout

• void merge(int *array,int l,int mid,int r){//cout