1. 程式人生 > >練習代碼——《算法(第四版)》(一)

練習代碼——《算法(第四版)》(一)

style .so oid 2.0 gcd main i++ java static

2017年11月20日。

  1 import java.util.Arrays;
  2 
  3 public class Program
  4 {
  5     public static void main(String[] args)
  6     {
  7 //        testBinarySearch(‘+‘);
  8         euclid(104, 24);
  9     }
 10 
 11     public static int gcd(int p, int q)
 12     {
 13         System.out.println("p: " + p + ", q: " + q);
14 if (q == 0) return p; 15 int r = p % q; 16 return gcd(q, r); 17 } 18 19 public static int lg(double n) 20 { 21 double m = Math.log(n) / Math.log(2.0); 22 return (int) Math.floor(m); 23 } 24 25 public static int[] histogram(int[] a, int
m) 26 { 27 int[] M = new int[m]; 28 for (int i = 0; i < a.length; i++) { 29 if (i == a[i]) 30 M[i] += 1; 31 } 32 return M; 33 } 34 35 public static int mystery(int a, int b) 36 { 37 if (b == 0) return 0;
38 if (b % 2 == 0) return mystery(a + a, b / 2); 39 return mystery(a + a, b / 2) + a; 40 } 41 42 public static long fibonacci(int n) 43 { 44 if (n == 0) return 0; 45 if (n == 1) return 1; 46 else return fibonacci(n - 2) + fibonacci(n - 1); 47 } 48 49 public static long fib(int n) 50 { 51 long f1 = 0; 52 long f2 = 1; 53 long tm = 0; 54 while (n > 0) { 55 tm = f1; 56 f1 = f1 + f2; 57 f2 = tm; 58 n--; 59 } 60 return f1; 61 } 62 63 public static double ln(int n) 64 { 65 if (n == 1) 66 return Math.log10(1); 67 else 68 return Math.log10(n) + ln(n - 1); 69 } 70 71 public static int binarySearch(int key, int[] arr, int lo, int hi, int n) 72 { 73 System.out.println("deep: " + n++); 74 if (lo > hi) return -1; 75 int mid = lo + (hi - lo) / 2; 76 if (key < arr[mid]) 77 return binarySearch(key, arr, lo, mid - 1, n); 78 else if (key > arr[mid]) 79 return binarySearch(key, arr, mid + 1, hi, n); 80 else 81 return mid; 82 } 83 84 public static int binarySearch(int key, int[] arr) 85 { 86 return binarySearch(key, arr, 0, arr.length, 0); 87 } 88 89 public static void testBinarySearch(char ch) 90 { 91 int[] arr = {11, 13, 15, 7, 9, 1, 3, 5, 17, 19, 21}; 92 Arrays.sort(arr); 93 for (int i = 0; i < arr.length; i++) { 94 System.out.print(arr[i] + (i < arr.length - 1 ? " " : "\n")); 95 } 96 int key = 18; 97 System.out.println(binarySearch(key, arr)); 98 } 99 100 public static void euclid(int p, int q) 101 { 102 int r = gcd(p, q); 103 System.out.println(r); 104 } 105 }

練習代碼——《算法(第四版)》(一)