|
| 1 | +def quick_sort(arr, start, end): |
| 2 | + """ |
| 3 | + Quick Sort algorithm: Sorts the array in ascending order. |
| 4 | + |
| 5 | + Parameters: |
| 6 | + arr (list): The list of elements to be sorted. |
| 7 | + start (int): The starting index of the array segment. |
| 8 | + end (int): The ending index of the array segment. |
| 9 | + """ |
| 10 | + if start < end: |
| 11 | + # Partition the array and get the pivot index |
| 12 | + pivot_index = partition(arr, start, end) |
| 13 | + |
| 14 | + # Recursively sort the left subarray |
| 15 | + quick_sort(arr, start, pivot_index - 1) |
| 16 | + |
| 17 | + # Recursively sort the right subarray |
| 18 | + quick_sort(arr, pivot_index + 1, end) |
| 19 | + |
| 20 | + |
| 21 | +def partition(arr, start, end): |
| 22 | + """ |
| 23 | + Partitions the array around a pivot such that all elements smaller than |
| 24 | + or equal to the pivot are on the left, and all elements greater are on the right. |
| 25 | + |
| 26 | + Parameters: |
| 27 | + arr (list): The list of elements to be partitioned. |
| 28 | + start (int): The starting index of the array segment. |
| 29 | + end (int): The ending index of the array segment (pivot). |
| 30 | + |
| 31 | + Returns: |
| 32 | + int: The index of the pivot element after partitioning. |
| 33 | + """ |
| 34 | + pivot = arr[end] # Choose the last element as the pivot |
| 35 | + partition_index = start # Initialize the partition index |
| 36 | + |
| 37 | + for i in range(start, end): |
| 38 | + if arr[i] <= pivot: |
| 39 | + # Swap if the current element is smaller than or equal to the pivot |
| 40 | + arr[i], arr[partition_index] = arr[partition_index], arr[i] |
| 41 | + partition_index += 1 |
| 42 | + |
| 43 | + # Place the pivot element at the correct position |
| 44 | + arr[partition_index], arr[end] = arr[end], arr[partition_index] |
| 45 | + return partition_index |
| 46 | + |
| 47 | + |
| 48 | +# Example Usage |
| 49 | +if __name__ == "__main__": |
| 50 | + # Input array |
| 51 | + array = [8, 3, 1, 7, 0, 10, 2] |
| 52 | + print("Original Array:", array) |
| 53 | + |
| 54 | + # Perform Quick Sort |
| 55 | + quick_sort(array, 0, len(array) - 1) |
| 56 | + |
| 57 | + # Output sorted array |
| 58 | + print("Sorted Array:", array) |
0 commit comments