You are on page 1of 3

Ex 9: Quick Sort Students By Height

To sort the students in the class according to their heights for group photo in
descending using quick sort algorithm.

ALGORITHM:
Input: List of students with their heights, start index, end index
Output: Sorted list of students in descending order based on height

1. Procedure quick_sort_students_by_height(students, start, end):


a. If start is less than end:
i. Call partition to obtain the pivot index.
ii. Recursively call quick_sort_students_by_height for the left subarray (start to
pivot_index - 1).
iii. Recursively call quick_sort_students_by_height for the right subarray (pivot_index +
1 to end).

2. Procedure partition(students, start, end):


a. Set pivot_height as students[end]['height'].
b. Initialize i as start - 1.
c. Iterate j from start to end - 1:
i. If students[j]['height'] is greater than or equal to pivot_height:
- Increment i.
- Swap students[i] with students[j].
d. Swap students[i + 1] with students[end].
e. Return i + 1 as the pivot index.

3. Example usage:
a. Initialize a list of students with dictionaries containing 'name' and 'height'.
b. Print the list before sorting.
c. Call quick_sort_students_by_height with the list of students, start index 0, and end index
len(students) - 1.
d. Print the list after sorting in descending order based on height.
PROGRAM:
def quick_sort_students_by_height(students, start, end):
if start < end:
# Partition the array and get the pivot index
pivot_index = partition(students, start, end)

# Recursively sort the subarrays on both sides of the pivot


quick_sort_students_by_height(students, start, pivot_index - 1)
quick_sort_students_by_height(students, pivot_index + 1, end)

def partition(students, start, end):


pivot_height = students[end]['height']
i = start - 1

for j in range(start, end):


if students[j]['height'] >= pivot_height:
i += 1
students[i], students[j] = students[j], students[i]

students[i + 1], students[end] = students[end], students[i + 1]


return i + 1

# Example usage:
if __name__ == "__main__":
students = [
{'name': 'Alice', 'height': 160},
{'name': 'Bob', 'height': 175},
{'name': 'Charlie', 'height': 165},
{'name': 'David', 'height': 180},
{'name': 'Eve', 'height': 155}
]

print("Before sorting:")
for student in students:
print(student)

quick_sort_students_by_height(students, 0, len(students) - 1)

print("\nAfter sorting in descending order:")


for student in students:
print(student)

OUTPUT:
Before sorting:
{'name': 'Alice', 'height': 160}
{'name': 'Bob', 'height': 175}
{'name': 'Charlie', 'height': 165}
{'name': 'David', 'height': 180}
{'name': 'Eve', 'height': 155}

After sorting in descending order:


{'name': 'David', 'height': 180}
{'name': 'Bob', 'height': 175}
{'name': 'Charlie', 'height': 165}
{'name': 'Alice', 'height': 160}
{'name': 'Eve', 'height': 155}

You might also like