{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

cs lecture nov 30

# cs lecture nov 30 - o(nlogn picking better...

This preview shows pages 1–3. Sign up to view the full content.

cs lecture nov 30 Quicksort Tony Houre, 1962 Basic idea -pick an element of the array array a, x = pivot element sort recursively eg. 0 7 [2][-10][14][42][11][-7][0][38] pick 2. sweep -> [0][-10][-7][2][11][14][42][38] <2 >2 recursively sort the two halves. How to partition? starting 0 [x][ ? ] two index variables: m,i 0 [x][ <x []][ >x ][] ? ] ^m ^i loop from i=1 to i=n-1 end [x][ <x][][ >=x ] <swap> ^m ^i=n [ <x ][x][ >=x] ^m void quicksort(int *a, int n) { int I, m, temp; if(n<=1) return; m=0; for(i=1;i<n;i++) if(a[i]<a[0]){

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
m++; temp=a[m]; a[m]=a[i]; a[i]=temp’ } temp=a[m]; a[m]=a[0]; a[0]=temp; quicksort(a,m); quicksort(a+(m+1),n-(m+1)); return; time complexity worst case[ <x ][x] o(n^2) time complexity “typical case” -> 50/50 split (more or less)
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: o(nlogn) picking better pivot?-random-median sf a sample better ways to partition, sweep to middle 0 1 2 n-1 ] qsort-library for sorting arrays (pp. 440-442) #include <stdlib.h> void qsort (void *base, size_t n, size_t size, int(*compare)(const void *a, const void b)); compares pointers to two elements return <0,=0,>0 int compInt(const void *a, const void *b) { int *p = (int &)a; int *q=(int*)b; return *p-*q; } #include <stdlib.h> int sort(int a, int n) { qsort(a,n,sizeof(int), compInt); } #include <stdio.h> int main(void) { int I; int a={2,-10,14,42,11,-7,-,39}; sort(a, 8); printf(“%d\n” a[3]); return 0; }...
View Full Document

{[ snackBarMessage ]}

### Page1 / 3

cs lecture nov 30 - o(nlogn picking better...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online