cs lecture nov 30

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

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

View Full Document Right Arrow Icon
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]){
Background image of page 1

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

View Full DocumentRight Arrow Icon
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)
Background image of page 2
Background image of page 3
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 &lt;stdlib.h&gt; void qsort (void *base, size_t n, size_t size, int(*compare)(const void *a, const void b)); compares pointers to two elements return &lt;0,=0,&gt;0 int compInt(const void *a, const void *b) { int *p = (int &amp;)a; int *q=(int*)b; return *p-*q; } #include &lt;stdlib.h&gt; int sort(int a, int n) { qsort(a,n,sizeof(int), compInt); } #include &lt;stdio.h&gt; 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

This note was uploaded on 12/10/2011 for the course CS 137 taught by Professor Clarke during the Fall '10 term at Waterloo.

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 Right Arrow Icon
Ask a homework question - tutors are online