cs lecture nov 23

cs lecture nov 23 - return; } void sort(int a,int n){ int...

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

View Full Document Right Arrow Icon
void sort (int a[], int n) { int I, j, min, temp; for (I =0; i<n-1;i++){ min=1; for(j=0;j<n;j++) if(a[j]<a[min] min=y; temp=a[min]; a[min]=a[i]; a[i]=temp; } } } } basic idea -divide array in half -sort each half -merge results [38][-7][14][11][-10][0][42] cut then sort -7,2,14,38 -10, 0, 11, 42 merge -10,-7,0,2,11,14,38,42 cut then sort again if necessary [-7][2][14][38] [11][-10][0][42] ^ ^ i(a) j(a+n/2) void mergeSort(int a[], in temp[].int n){ int i,j,k;S if (n<=1) return; mergeSort(a, temp, n/2); mergeSort(a+n/2,temp,n-n/2); i=0; j=n/2; k=0; if(a[i]<a[j]) temp[k++]=a[i++]; else temp[k++]a[j++]; } while(i<n/2){ temp[k++]=a[i++];
Background image of page 1

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

View Full DocumentRight Arrow Icon
} while[j<n){ temp[k++]=a[j++]; } for(i=0;i<n;i++) a[i]=temp[i];
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: return; } void sort(int a,int n){ int *temp=(int *)safemalloc(n*sizeof(int)); mergeSort(a, temp. n); free(temp); return; } time complexity suppose n=2^k&lt;n=2,4,8,16,32, k=1,2,3,4,5) array of size z splits into 2, of size n/2 splits into 4 size n/4 .. splits into n, size 1; n(nk)=0(nlog_2 n ) =O(nlogn) sorting selection, bubble, shell, insertion, O(n^2) mergeSort O(nlogn) fibonnaci numbers, 0,1,1,2,3,5,8 fn=0, if n=0. 1 if n=1, fn-1 + fn-2 if n&gt;1 int f(int n) { if(n&lt;=0) return 0; else if (n==1) return 1; else return f(n-2) + f(n-1); } f(32) 1 sec f(42 ) 6 sec f(45) 23 sec f(48) 2 min exponential...
View Full Document

Page1 / 3

cs lecture nov 23 - return; } void sort(int a,int n){ int...

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