{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

notes01

# notes01 - CSE 2320 Notes 1 Algorithmic Concepts(Last...

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

CSE 2320 Notes 1: Algorithmic Concepts (Last updated 3/26/12 13:56 A3/P3) 1.A. A S IMPLE A LGORITHMIC P ROBLEM - M AINTAINING D ISJOINT S UBSETS Sedgewick 1.2 and 1.3 Abstraction: Set of n elements: 0 . . n - 1 Initially all elements are in n different subsets find(i) - Returns integer (“leader”) indicating which subset includes i i and j are in the same subset find(i)==find(j) union(i,j) - Takes the set union of the subsets with leaders i and j . Implementation 1: ( uf1.c ) Initialization: for (i=0; i<n; i++) id[i]=i; find(i) : return id[i]; unionFunc(i,j) : for (k=0; k<n; k++) if (id[k]==i) id[k]=j; 0 1 2 3 4 0 1 2 3 4 Implementation 2: ( uf2.c ) find(i) : while (id[i]!=i) i=id[i]; return i; unionFunc(i,j) : id[i]=j; 0 1 2 3 4 0 1 2 3 4

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

View Full Document
Implementation 3: ( uf3.c ) Initialization: for (i=0; i<n; i++) { id[i]=i; sz[i]=1; } find(i) : while (id[i]!=i) i=id[i]=id[id[i]]; // =id[id[i]] is optional return i; unionFunc(i,j) : if (sz[i]<sz[j]) { id[i]=j; sz[j]+=sz[i]; } else { id[j]=i; sz[i]+=sz[j]; } Best-case (shallow tree) and worst-case (deep tree) for a sequence of unions? 1.B. Q UADRATIC T IME S ORT S : Selection Sort (Sedgewick 6.3) void selection(Item a[], int ell, int r) { int i, j; for (i = ell; i < r; i++) { int min = i; for (j = i+1; j <= r; j++) if (less(a[j], a[min])) min = j; exch(a[i], a[min]); } } Always uses i - 1 ( ) i =2 n å = i i =1 n -1 å = n n - 1 ( ) 2 » n 2 2 comparisons and is not stable . 2
Insertion Sort with Sentinel for Inner Loop (Sedgewick 6.4) void insertion(Item a[], int ell, int r) { int i; for (i = ell+1; i <= r; i++) compexch(a[ell], a[i]); for (i = ell+2; i <= r; i++) { int j = i; Item v = a[i]; while (less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } } Maximum (“worst case”) number of times that body of j -loop executes for a particular value of i ? Maximum number of times that body of j -loop executes over entire sort? i i =1 k å = k ( k +1) 2 = ? Expected (“average”) number of times that body of j -loop executes for a particular value of i ?

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}