Java作為一門強大的編程語言,在常用算法分析與實現方面也有非常豐富的資源。以下是幾種常用的算法及其Java實現。
1. 快速排序
public static void quickSort(int[] arr, int left, int right) { if (left >= right) { return; } int pivot = arr[(left + right) / 2]; int index = partition(arr, left, right, pivot); quickSort(arr, left, index - 1); quickSort(arr, index, right); } private static int partition(int[] arr, int left, int right, int pivot) { while (left<= right) { while (arr[left]< pivot) { left++; } while (arr[right] >pivot) { right--; } if (left<= right) { swap(arr, left, right); left++; right--; } } return left; } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
2. 歸并排序
public static void mergeSort(int[] arr, int left, int right) { if (left == right) { return; } int mid = (left + right) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } private static void merge(int[] arr, int left, int mid, int right) { int[] temp = new int[arr.length]; int i = left; int j = mid + 1; int k = left; while (i<= mid && j<= right) { if (arr[i]< arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } } while (i<= mid) { temp[k++] = arr[i++]; } while (j<= right) { temp[k++] = arr[j++]; } for (int l = left; l<= right; l++) { arr[l] = temp[l]; } }
3. 二分查找
public static int binarySearch(int[] arr, int key) { int start = 0; int end = arr.length - 1; while (start<= end) { int mid = (start + end) / 2; if (key == arr[mid]) { return mid; } else if (key< arr[mid]) { end = mid - 1; } else { start = mid + 1; } } return -1; }
4. 斐波那契數列
public static int fibonacci(int n) { if (n<= 1) { return n; } int fib = 1; int prevFib = 1; for (int i = 2; i< n; i++) { int temp = fib; fib += prevFib; prevFib = temp; } return fib; }
總結
以上是幾種常用的算法及其Java實現,它們在不同的場景中發揮著重要的作用。在編寫算法時,我們需要結合具體的應用場景,選擇合適的算法,并通過不斷優化和改進提高算法的效率。