a sample code for quick sort
时间: 2023-09-14 16:11:26 浏览: 110
Here is a sample code for Quick Sort in Python:
```
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
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)
arr = [5, 1, 9, 3, 7, 6, 8, 2, 4]
sorted_arr = quick_sort(arr)
print(sorted_arr)
```
This code defines a function called `quick_sort` that takes an array `arr` as input and returns a sorted array using the Quick Sort algorithm.
The function first checks if the length of the array is less than or equal to 1, in which case it simply returns the array as it is already sorted.
If the length of the array is greater than 1, the function selects the first element of the array as the pivot and creates two empty arrays called `left` and `right`.
Next, the function loops through the remaining elements of the array and adds them to either the `left` or `right` array depending on whether they are less than or greater than the pivot.
Finally, the function recursively calls itself on the `left` and `right` arrays and concatenates the sorted `left` array, the pivot, and the sorted `right` array to produce the final sorted array.
The code then creates an example array `arr`, calls the `quick_sort` function on it to obtain a sorted array, and prints the result.
阅读全文