Write python code for Quick sort.
Quick Sort:
Here's an implementation of Quick Sort algorithm in Python:
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[0] left = [] right = [] for i in range(1, len(arr)): if arr[i] < pivot: left.append(arr[i]) else: right.append(arr[i]) return quick_sort(left) + [pivot] + quick_sort(right)
The above code defines a function quick_sort()
that takes an array as input and returns a sorted array using the Quick Sort algorithm.
The quick_sort()
function first checks if the length of the array is less than or equal to 1. If that's the case, it simply returns the array because it's already sorted.
Next, it selects the first element of the array as the pivot element. It then iterates through the array from the second element to the last element, and puts all elements smaller than the pivot into the left
array, and all elements greater than or equal to the pivot into the right
array.
Finally, it returns the concatenation of quick_sort(left)
, [pivot]
, and quick_sort(right)
to obtain the sorted array.
To test the quick_sort()
function, you can call it with an array as an argument:
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr = quick_sort(arr) print(sorted_arr)
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
.
No comments: