0% found this document useful (0 votes)
24 views

Quick, Merge and Counting Sort of Array

The document describes the merge sort algorithm. It divides the unsorted list recursively in half until reaching lists with single elements, sorts those and then merges the sorted halves back together.

Uploaded by

King Shah 673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Quick, Merge and Counting Sort of Array

The document describes the merge sort algorithm. It divides the unsorted list recursively in half until reaching lists with single elements, sorts those and then merges the sorted halves back together.

Uploaded by

King Shah 673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Step 1 − Choose the highest index value has pivot

Step 2 − Take two variables to point left and right of the list
excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left
and right
Step 8 − if left ≥ right, the point where they met is new pivot
Quick Sort
15 20 35 10 25 55 50 45 40 30

15 20 10 25 30 35 55 50 45 40

10 15 20 25 30 35 40 45 50 55

10 15 20 25 30 35 40 45 50 55

10 15 20 25 30 35 40 45 50 55
Quick sort Algorithm
Merge Sort
• Merging a two lists of one element each is the
same as sorting them.
• Merge sort divides up an unsorted list until
the above condition is met and then sorts the
divided parts back together in pairs.
• Specifically, this can be done by recursively
dividing the unsorted list in half, merge sorting
the right side then the left side and then
merging the right and left back together.
Pseudo Code of Merge Sort
Given a list L with a length k:
• If k == 1 → the list is sorted
• Else:
– Recursively Sort the left side (0 to k/2)
– Recursively Sort the right side (k/2+1 to k)
– Merge the right side with the left side
Merge Sort
Merge Sort
Merge sort (A)
{
n=length(A)
if n<2 Return

mid=n/2
left=array of size (mid)
right=array of size (n-mid)

for i from 0 to mid-1


left[i]=A[i]

for i from mid to n-1


right[i]=A[i]

merge sort(left)
merge sort(right)
merge(left, right, A)
}
Merge Sort
merge(left, right, A)
{
nL=len(left)
nR=len(right)
i=j=k=0

while (i<nL && j<nR) while(i<nL)


if (left[i]<=right[j]) A[k]=left[i]
A[k]=left[i] k++
i++ i++
else while(j<nR)
A[k]=right[j] A[k]=right[j]
j++ k++
j++
k=k+1
}

You might also like