Quicksortdef

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Powered by AI

Bing

QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an element as a pivot
and partitions the given array around the picked pivot. The key process in QuickSort is partitioning. The target
of partitions is to place the pivot at its correct position in the sorted array and put all smaller elements to the
left of the pivot, and all greater elements to the right of the pivot.

Here’s a step-by-step breakdown of how QuickSort works:

1. Choose a Pivot: There are many different choices for picking pivots. You can always pick the first
element as a pivot, always pick the last element as a pivot, pick a random element as a pivot, or pick the
middle as the pivot.

2. Partition the Array: The elements of the array are rearranged so that elements that are smaller than the
pivot are put on the left and the elements greater than the pivot are put on the right.

3. Recursively Apply QuickSort: Pivot elements are again chosen for the left and the right sub-parts
separately. And, step 2 is repeated. The subarrays are divided until each subarray is formed of a single
element. At this point, the array is already sorted.

Here’s a Python code snippet that implements QuickSort:

def partition(arr, low, high):


pivot = arr[high]
i = (low - 1)
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i + 1)

def quickSort(arr, low, high):


if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi - 1)
quickSort(arr, pi + 1, high)

arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:", arr)

This code will output: Sorted array is: [1, 5, 7, 8, 9, 10].

The time complexity of QuickSort is as follows:

Best Case: Ω(n log n)


Average Case: Θ(n log n)
Worst Case: O(n²)

The space complexity of QuickSort is O(log n)…

You might also like