Skip to content

Commit

Permalink
Merge pull request #380 from ruchikakengal/Add-Quick-sort
Browse files Browse the repository at this point in the history
Add  Quick Sort Problem
  • Loading branch information
PRIYESHSINGH24 authored Jan 20, 2025
2 parents 4550367 + 8ef16dd commit 3528e6b
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Geeks For Geeks/Sorting problems/Quick sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

def quick_sort(arr):
"""
Main function to perform Quick Sort.
This function calls the helper function to sort the array using the divide-and-conquer strategy.
"""
print(f"Initial Array: {arr}")
sorted_array = quick_sort_recursive(arr, 0, len(arr) - 1)
print(f"Sorted Array: {sorted_array}")
return sorted_array

def quick_sort_recursive(arr, low, high):
"""
Recursive helper function for Quick Sort.
It partitions the array into subarrays and sorts them recursively.
"""
if low < high:
# Partition the array and get the pivot index
pivot_index = partition(arr, low, high)
print(f"Array after partitioning: {arr}, Pivot Index: {pivot_index}")

# Recursively sort elements before and after partition
quick_sort_recursive(arr, low, pivot_index - 1)
quick_sort_recursive(arr, pivot_index + 1, high)

return arr

def partition(arr, low, high):
"""
Partition the array around a pivot element.
Elements smaller than the pivot are moved to the left, and elements greater are moved to the right.
"""
pivot = arr[high] # Choose the last element as pivot
print(f"Using Pivot: {pivot} (from index {high})")
i = low - 1 # Pointer for the smaller element

# Traverse through the array and compare each element with the pivot
for j in range(low, high):
print(f"Comparing: {arr[j]} with Pivot: {pivot}")
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i] # Swap
print(f"Swapped: {arr[i]} and {arr[j]}, Updated Array: {arr}")

# Place the pivot element in the correct position
arr[i + 1], arr[high] = arr[high], arr[i + 1]
print(f"Placing Pivot: {pivot} at correct position, Updated Array: {arr}")
return i + 1

# Example Usage
array = [10, 7, 8, 9, 1, 5]
print("Quick Sort Example")
quick_sort(array)

0 comments on commit 3528e6b

Please sign in to comment.