QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot.
Java
public class Sort{ public static void main(String []args){ int[] arr = {3, 5, 1, 6, 2, 4, 8}; quickSort(arr, 0, arr.length-1); for(int x:arr) System.out.print(x+" "); } public static int partition(int arr[], int low, int high){ int pivot = arr[high]; int i = (low-1); for (int j=low; j<high; j++){ if (arr[j] <= pivot){ i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } public static void quickSort(int arr[], int low, int high){ if (low < high){ int pi = partition(arr, low, high); quickSort(arr, low, pi-1); quickSort(arr, pi+1, high); } } }
Python
def quickSort(arr): less = [] pivotList = [] more = [] if len(arr) <= 1: return arr else: pivot = arr[0] for i in arr: if i < pivot: less.append(i) elif i > pivot: more.append(i) else: pivotList.append(i) less = quickSort(less) more = quickSort(more) return less + pivotList + more arr = [3, 5, 1, 6, 2, 4] print(quickSort(arr)) |