|
CS 3343/3341 Analysis of Algorithms Fall 2012 Recitation 4 In-Class Problems Week 4: Sep 18-20 |
| ^ | 0 1 2 3 4 5 6 7 8 9 10 11 12 -----------|------------------------------------------------------------------ Array | 16 19 9 5 13 8 7 4 21 2 6 11 18 | Partition 1| 16 9 5 13 8 7 4 2 6 11 18 19 21 | Subarray 1 | 16 9 5 13 8 7 4 2 6 11 (18) (19) (21) | Partition 2| 9 5 8 7 4 2 6 11 16 13 (18) (19) (21) | Subarray 2 | 9 5 8 7 4 2 6 (11) (16) (13) (18) (19) (21) | Partition 3| 5 4 2 6 9 8 7 (11) (16) (13) (18) (19) (21) | Subarray 3 | (5) (4) (2) (6) 9 8 7 (11) (16) (13) (18) (19) (21) | Partition 4| (5) (4) (2) (6) 7 8 9 (11) (16) (13) (18) (19) (21) | Subarray 4 | (5) (4) (2) (6) (7) 8 9 (11) (16) (13) (18) (19) (21) | Partition 5| (5) (4) (2) (6) (7) 8 9 (11) (16) (13) (18) (19) (21) | |
// Median.java: finds median value public class Median { public int median(int[] A, int p, int r, int mid) { printa(A, p, r); int pivot = partition(A, p, r); printa(A, p, r); if (mid == pivot) return A[mid]; else if (mid < pivot) return median(A, p, pivot-1, mid); else return median(A, pivot+1, r, mid); } public int partition(int[] A, int p, int r) { int x = A[r]; int i = p - 1; for (int j = p; j < r; j++) { if (A[j] <= x) { i++; exchange(A,i, j); } } exchange(A, i+1, r); return i + 1; } private void exchange(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } | private void printa(int[] A, int p, int r) { int i = 0; while (i < p) printn2(A[i++]); for (i = p; i <= r; i++) printn1(A[i]); i = r+1; while (i <= A.length - 1) printn2(A[i++]); System.out.println(); } void printn1(int i) { if (i < 10) System.out.print(" " + i + " "); else System.out.print(" " + i + " "); } void printn2(int i) { if (i < 10) System.out.print(" (" + i + ")"); else System.out.print(" (" + i + ")"); } public static void main(String[] args) { int[] A = {43,22,51,19,11,67,13,36,32,49,28,15,38}; Median med = new Median(); System.out.println("Median:" + med.median(A,0,A.length-1,(A.length-1)/2)); } } |
0 | 0 1 2 3 4 5 6 7 8 9 10 11 12 -----------|------------------------------------------------------------------ Array | 43 22 51 19 11 67 13 36 32 49 28 15 38 | Partition 1| 22 19 11 13 36 32 28 15 38 49 43 51 67 | Subarray 1 | 22 19 11 13 36 32 28 15 (38) (49) (43) (51) (67) | Partition 2| 11 13 15 19 36 32 28 22 (38) (49) (43) (51) (67) | Subarray 2 | (11) (13) (15) 19 36 32 28 22 (38) (49) (43) (51) (67) | Partition 3| (11) (13) (15) 19 22 32 28 36 (38) (49) (43) (51) (67) | Subarray 3 | (11) (13) (15) (19) (22) 32 28 36 (38) (49) (43) (51) (67) | Partition 4| (11) (13) (15) (19) (22) 32 28 36 (38) (49) (43) (51) (67) | Subarray 4 | (11) (13) (15) (19) (22) 32 28 (36) (38) (49) (43) (51) (67) | Partition 5| (11) (13) (15) (19) (22) 28 32 (36) (38) (49) (43) (51) (67) | Subarray 5 | (11) (13) (15) (19) (22) (28) 32 (36) (38) (49) (43) (51) (67) | Partition 5| (11) (13) (15) (19) (22) (28) 32 (36) (38) (49) (43) (51) (67) | Median: 32 |