Algo Lab5- Revision and Quicksort
Algo Lab5- Revision and Quicksort
Lab 5
Recursion Recap
Function calls itself for one or more times
Consists of two parts:
- Recursive part
- Base case (stopping condition)
Fun(…)
General form: ….
Base Case
….
Fun(…), Fun(…), …etc Recursive Code
Normal Code
….
….
Theory of algorithms Lab4
How to Analyze Recursive
Code?
1. Calculate Running Time T(N) [Recurrence]
T(N) = Time of Normal Code + T(Recursive Code) + … etc
T(Base) = Time of Base Case
Not on a form
Cannot solve by master method
2. Partition the Array: Rearrange the array around the pivot. After partitioning, all
elements smaller than the pivot will be on its left, and all elements greater than the
pivot will be on its right. The pivot is then in its correct position, and we obtain the
index of the pivot.
3. Recursively Call: Recursively apply the same process to the two partitioned sub-arrays
(left and right of the pivot).
Base Case: The recursion stops when there is only one element left in the sub-array, as a
single element is already sorted.
Pseudocode Quicksort Function
• A → The array.
• p → The starting index of the section
being partitioned.
• r → The last index (pivot).
• x → The pivot element (A[r]).
• i → The boundary between smaller and
larger elements.
• j → The index scanning through the
array.
Pseudocode Partition
Function(Cont.)
•x = A[r] → Choose the last element (A[r]) as the pivot.
•i = p - 1 → Set i to one position before the starting index (p).
•Loop j = p to r - 1 → Move through the array up to the pivot.
•If A[j] ≤ x → If A[j] is smaller than or equal to the pivot:
•Move the i pointer forward (i = i + 1).
•Swap A[i] with A[j].
•After the loop,
•swap A[i + 1] with A[r] → Put the pivot in its correct place.
•Return i + 1 → This is the final index of the pivot.
Summary of Quicksort
pseudocode
•QuickSort recursively sorts the left and right sides after partitioning.
•Partition rearranges the elements so that the pivot is in the correct position.
•Every letter in the pseudocode has a clear role:
•A (Array),
•p (Start),
• r (End),
•x (Pivot),
• i (Smaller boundary),
• j (Iterator),
• q (Pivot final index).
Example
to:[2, 8, 7, 1, 3, 5, 6, 4]
• Initial Values:
p = 0 (First index)
r = 7 (Last index)
Pivot = 4 (A[r])
Step 1: Partitioning Process
We start PARTITION(A, 0, 7) with pivot 4.
After partitioning, the pivot 4 is at index 3. After partitioning, the pivot 4 is at index 3.
2: Recursively Apply Quicksort
(Left)
Quicksort on Left Side [2, 1, 3]
Pivot: 3 (A[2])
Sorted: [1, 2, 3]
2: Recursively Apply Quicksort
(Right)
Quicksort on Right Side [7, 5, 6, 8]
Pivot: 8 (A[7])
Sorted: [5, 6, 7, 8]
Final Sorted Array [1, 2, 3, 4, 5, 6, 7, 8]