Void Pivot(Int a , Int Left, Int Right)

Total Page:16

File Type:pdf, Size:1020Kb

Void Pivot(Int a , Int Left, Int Right)

Quicksort

void Swap(int &a, int &b){ int temp = a; a = b; b = temp; }

void Pivot(int a[], int left, int right){ if (a[left] > a[right]) Swap(a[left], a[right]); }

int Partition(int a[], int left, int right){ int pivot = a[left]; int i = left; int j = right+1; do{ do{ ++i; }while(a[i] < pivot); do{ --j; }while(a[j] > pivot); if (i < j) Swap(a[i], a[j]); }while (i < j); Swap(a[j], a[left]); return j; }

void quicksort(int array[], int left, int right){ if (left < right){ Pivot(array, left, right); int k = Partition(array, left, right); quicksort (array, left, k-1); quicksort (array, k+1, right); } }

C++ Quicksort © 2001 B. Tjaden 1 void printarray(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl << endl; }

 quicksort has best-case, average-case and arbitrary-case performances of O(nlogn)

 worst case performance o O(n2) o occurs when array is in reverse or nearly reverse sorted order

 quicksort o begins by choosing a pivot point o the list is then rearranged into 3 sublists or partitions . left partition contains elements smaller than array[pivot] . middle partition is array[pivot] . right partition contains elements larger than array[pivot] o left and right sublists are sorted independently . with recursive calls to quicksort o left is the leftmost element in the list or sublist o right is the rightmost element in the list or sublist

C++ Quicksort © 2001 B. Tjaden 2

Recommended publications