# Sorting Algorithms: Quicksort, Merge Sort, and Radix Sort ## Quicksort Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted. ```python def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) ``` ## Merge Sort Merge Sort is a divide and conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The `merge()` function is used to merge two halves. ```python def mergeSort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] mergeSort(L) mergeSort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 ``` ## Radix Sort Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits at significant places. ```python def countingSort(arr, exp1): n = len(arr) output = [0] * (n) count = [0] * (10) for i in range(0, n): index = (arr[i] / exp1) count[int((index) % 10)] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = (arr[i] / exp1) output[count[int((index) % 10)] - 1] = arr[i] count[int((index) % 10)] -= 1 i -= 1 for i in range(0, len(arr)): arr[i] = output[i] def radixsort(arr): max1 = max(arr) exp = 1 while max1 / exp > 0: countingSort(arr, exp) exp *= 10 ```