递归(二)
分治算法:
递归的二分查找就是分治算法的一个例子。把一个大问题分成两个相对更小的问题,并且去解决每一个小问题。对每一个小问题也是同样的解决方法:再把每个小问题分成更小的问题,并且解决它们。这个过程一直持续下去。
分治算法常常是一个方法,而这个方法含有两个对自身的调用,分别对应于问题的两个部分。
归并排序:
1 public class DArray { 2 3 private int[] array; 4 5 private int maxLength; 6 7 public DArray(int size) { 8 array = new int[size]; 9 maxLength = 0; 10 } 11 12 public void insert(int d) { 13 array[maxLength++] = d; 14 } 15 16 public void mergeSort() { 17 int[] workSpace = new int[maxLength]; 18 recMergeSort(workSpace, 0, maxLength - 1); 19 } 20 21 private void recMergeSort(int[] workSpace, int lower, int upper) { 22 if (lower == upper) { 23 return; 24 } 25 int mid = (lower + upper) / 2; 26 recMergeSort(workSpace, lower, mid); 27 recMergeSort(workSpace, mid + 1, upper); 28 merge(workSpace, lower, mid + 1, upper); 29 } 30 31 private void merge(int[] workSpace, int lowerPatr, int highPatr, int upper) { 32 int j = 0; 33 int lower = lowerPatr; 34 int mid = highPatr - 1; 35 int n = upper - lower + 1; 36 37 while (lowerPatr <= mid && highPatr <= upper) { 38 if (array[lowerPatr] < array[highPatr]) 39 workSpace[j++] = array[lowerPatr++]; 40 else 41 workSpace[j++] = array[highPatr++]; 42 } 43 44 while (lowerPatr <= mid) { 45 workSpace[j++] = array[lowerPatr++]; 46 } 47 while (highPatr <= upper) { 48 workSpace[j++] = array[highPatr++]; 49 } 50 51 for (int k = 0; k < n; k++) { 52 array[lower + k] = workSpace[k]; 53 } 54 55 } 56 57 public void display() { 58 for (int i = 0; i < maxLength; i++) { 59 System.out.println("NO." + (i + 1) + " --> " + array[i]); 60 } 61 } 62 63 }
1 public static void main(String[] args) { 2 DArray array = new DArray(12); 3 array.insert(61); 4 array.insert(5); 5 array.insert(15); 6 array.insert(45); 7 array.insert(25); 8 array.insert(99); 9 array.insert(3); 10 array.insert(37); 11 array.insert(84); 12 array.insert(16); 13 array.insert(7); 14 15 array.mergeSort(); 16 array.display(); 17 }
打印结果:
NO.1 --> 3
NO.2 --> 5
NO.3 --> 7
NO.4 --> 15
NO.5 --> 16
NO.6 --> 25
NO.7 --> 37
NO.8 --> 45
NO.9 --> 61
NO.10 --> 84
NO.11 --> 99