Quick N Merge
Quick N Merge
39 9 81 45 90 27 72 18
39 9 81 45 90 27 72 18
90 27 72 18
39 9 81 45
72
39 9 81 45 90 27 18
9 39 45 81 27 90 18 72
9 39 45 81 18 27 72 90
9 18 27 39 45 72 81 90
TEMP
INDEX
9 39 45 81 18 27 72 90
9 18
INDEX
9 39 45 81 18 27 72 90
BEG I Mid J END
TEMP
9 18 27
INDEX
9 39 45 81 18 27 72 90
BEG I Mid J END
TEMP
9 18 27 39
INDEX
Merge Sort
9 39 45 81 18 27 72 90
9 18 27 39 45
INDEX
9 39 45 81 18 27 72 90
9 18 27 39 45 72
INDEX
When I is greater than MID copy the remaining elements of the right sub-array in TEMP
9 18 27 39 45 72 72 81 90
INDEX
Merge Sort
MERGE (ARR, BEG, MID, END)
• Set the index of the first element in the array to loc and left variables. Also set
the index of the last element of the array to the right variable.
• That is, loc =0, left = 0 and right = n-1 (where n in the number of elements in the
array)
• Start from the element pointed by right and scan the array from right to left,
comparing each element on the way with the element pointed by variable loc.
• That is, a[loc]should be less than a[right]. If that is the case then simply continue
comparing until right becomes equal to loc. Because once right = loc, then it
means the pivot has been placed in its correct position.
Quick Sort
• However, if at any point we have a[loc]>a[right] then, interchange the two
values and jump to step 3.
• If that is the case then simply continue comparing until left becomes equal
to loc. Because once left = loc, then it means the pivot has been placed in
its correct position.
Loc Right
Left
Scan from right to left. Since a[loc] < a[right], decrease the value of right.
27 10 36 18 25 45
Loc Right
Left
Quick Sort
Since, a[loc] > a[right], interchange the two values and set loc = right.
25 10 36 18 27 45
25 10 36 18 27 45
Left
Right, Loc
Quick Sort
Start scanning from left to right. Since, a[loc] > a[right], increment
the value of left.
25 10 36 18 27 45
Left
Right, Loc
Now since, a[loc] < a[right], interchange the values and set loc = left
25 10 27 18 36 45
Left, Loc
Right,
Quick Sort
Scan from right to left. Since a[loc] < a[right], decrement the value of
right.
25 10 27 18 36 45
Since, a[loc] > a[right], interchange the two values and set loc =
right. 25 10 18 27 36 45
Start scanning from left to right. Since, a[loc] > a[right], increment
the value of left. 25 10 18 27 36 45
Step 1: [Initialize] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG = 0
Step 2: Repeat Steps 3 to while FLAG = 0
Step 3: Repeat while ARR[LOC] <= ARR[RIGHT] AND LOC != RIGHT
SET RIGHT = RIGHT – 1
[END OF LOOP]
Step 4: IF LOC == RIGHT, then
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT], then
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT
[END OF IF]
Step 5: IF FLAG = 0, then
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1
[END OF LOOP]
Step 6: IF LOC == LEFT, then
SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT], then
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]
Step 7: [END OF LOOP]
Step 8: END
Quick Sort