quick sort wiki code example

Example 1: quicksort

// @see https://www.youtube.com/watch?v=es2T6KY45cA&vl=en
// @see https://www.youtube.com/watch?v=aXXWXz5rF64
// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html

function partition(list, start, end) {
    const pivot = list[end];
    let i = start;
    for (let j = start; j < end; j += 1) {
        if (list[j] <= pivot) {
            [list[j], list[i]] = [list[i], list[j]];
            i++;
        }
    }
    [list[i], list[end]] = [list[end], list[i]];
    return i;
}

function quicksort(list, start = 0, end = undefined) {
    if (end === undefined) {
        end = list.length - 1;
    }
    if (start < end) {
        const p = partition(list, start, end);
        quicksort(list, start, p - 1);
        quicksort(list, p + 1, end);
    }
    return list;
}

quicksort([5, 4, 2, 6, 10, 8, 7, 1, 0]);

Example 2: analysis of quick sort

T(n) = 2*T(n/2) + n                        // T(n/2) = 2*T(n/4) + (n/2)    

        = 2*[ 2*T(n/4) + n/2 ] + n
	= 22*T(n/4) + n + n
	= 22*T(n/4) + 2n                       // T(n/4) = 2*T(n/8) + (n/4)

	= 22*[ 2*T(n/8) + (n/4) ] + 2n
	= 23*T(n/8) + 22*(n/4) + 2n
	= 23*T(n/8) + n + 2n
	= 23*T(n/8) + 3n

	= 24*T(n/16) + 4n
	and so on....

	= 2k*T(n/(2k)) + k*n      // Keep going until: n/(2k) = 1  <==> n = 2k    

	= 2k*T(1) + k*n
	= 2k*1 + k*n
	= 2k + k*n               // n = 2k
	= n + k*n
	= n + (lg(n))*n
        = n*( lg(n) + 1 )
       ~= n*lg(n))

Example 3: quick sort

#include<stdio.h>
int partition(int arr[], int low, int high) {
  int temp;
  int pivot = arr[high];
  int i = (low - 1); 
  for (int j = low; j <= high - 1; j++) {
    if (arr[j] <= pivot) { 
      i++; 
      temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    } 
  } 
  temp = arr[i + 1];
  arr[i + 1] = arr[high];
  arr[high] = temp;
  return (i + 1); 
} 
void quick_sort(int arr[], int low, int high) { 
  if (low < high) {
    int pi = partition(arr, low, high); 
    quick_sort(arr, low, pi - 1); 
    quick_sort(arr, pi + 1, high); 
  } 
} 
int print(int arr[], int n) {
  for(int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
}

int main()
{
int n, i;
scanf("%d", &n);
int arr[n];
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
quick_sort(arr, 0, n - 1);
print(arr, n);
}

Tags:

Cpp Example