Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Added the Python Program] - added the Quick Sort Program in python #84

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions python/Quick_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Function to swap two elements
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]

# Partition function to rearrange the array
def partition(arr, low, high):
pivot = arr[high] # Pivot element (typically the last element)
i = low - 1 # Index of the smaller element

for j in range(low, high):
# If current element is smaller than or equal to pivot
if arr[j] <= pivot:
i += 1
swap(arr, i, j) # Swap smaller element with element at i

swap(arr, i + 1, high) # Place the pivot in its correct position
return i + 1 # Return the partition index

# Quick Sort function
def quick_sort(arr, low, high):
if low < high:
# pi is the partition index
pi = partition(arr, low, high)

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

# Utility function to print an array
def print_array(arr):
for i in arr:
print(i, end=" ")
print()

# Main function to test the quick sort
if __name__ == "__main__":
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)

print("Unsorted array:")
print_array(arr)

# Perform Quick Sort
quick_sort(arr, 0, n - 1)

print("Sorted array:")
print_array(arr)