110 likes | 225 Views
CSC 205 Java Programming II. Runtime Analysis. Selection Sort. 10 8 6 2 16 4 18 11 14 12. Select the largest element, big , of the n elements. n elements. first. 10 8 6 2 16 4 18 11 14 12. 2. Swap the last element with big.
E N D
CSC 205 Java Programming II Runtime Analysis
Selection Sort 10 8 6 2 16 4 18 11 14 12 • Select the largest element, • big, of the n elements n elements first 10 8 6 2 16 4 18 11 14 12 2. Swap the last element with big 3. Continue with the remaining n-1 elements, [first] to [first + n - 2]
The Selection Sort Algorithm public static void selectionSort(int[ ] data, int first, int n){ int i, j; int big; int temp; for (i = n-1; i > 0; i--) { big = first; for (j = first+1; j <= first+i; j++) if (data[big] < data[j]) big = j; temp = data[first+i]; data[first+i] = data[big]; data[big] = temp; } }
Number of Operations • Outer loopfor (int i=n-1; i>0; i--) swap(data[first+i], data[ibig]); • Comparison: i>0 • Assignments: in swap • Calculation: first+I • Decrement: i-- • Total # of operations: • (n-1) * (constant time + cost of finding i_big)
Divide and Conquer • Divide the dataset into two subsets of equal or nearly equal size • Sort each subset by recursive calls • Combine the two sorted subsets into one larger sorted set
Merge Sort • Cut the dataset into halves, each with n/2 and n-n/2 items 10 8 6 2 16 4 18 11 14 12 10 8 6 2 16 4 18 11 14 12 ... ... ... ... 10 8 ... ... ... ... 12
Merge Sort • Use recursive calls to solve the two halves 10 8 ... ... ... ... 14 12 8 10 12 14 • Merge ... ... ... ... 2 6 8 10 16 4 11 12 14 18 2 4 6 8 10 11 12 14 16 18
The Merge Sort Algorithm public static void mergeSort(int[ ] data, int first, int n) { int n1; // Size of the first half of the array int n2; // Size of the second half of the array if (n > 1) { n1 = n / 2; n2 = n - n1; mergesort(data, first, n1); mergesort(data, first + n1, n2); merge(data, first, n1, n2); } }
The merge Method private static void merge(int[ ] data, int first, int n1, int n2) { int[ ] temp = new int[n1+n2]; int copied = 0; int copied1 = 0; int copied2 = 0; int i; while ((copied1 < n1) && (copied2 < n2)) { if (data[first + copied1] < data[first + n1 + copied2]) temp[copied++] = data[first + (copied1++)]; else temp[copied++] = data[first + n1 + (copied2++)]; } while (copied1 < n1) temp[copied++] = data[first + (copied1++)]; while (copied2 < n2) temp[copied++] = data[first + n1 + (copied2++)]; for (i = 0; i < n1+n2; i++) data[first + i] = temp[i]; }
Runtime Analysis for Merge Sort 10 8 6 2 16 4 18 11 14 12 10 8 6 2 16 4 18 11 14 12 h ... ... ... ... h = log n 10 8 ... ... ... ... 12 n
n2 vs. n log2n • nn log2n n2dgsgsdgsdg • 2 2 2 • 8 24 64 • 32 160 1024 • 128 896 16384 • 512 4608 262144 • 2048 22528 4194304