当涉及排序算法时,Java中常见的五种排序算法包括冒泡排序、选择排序、插入排序、归并排序和快速排序。以下是用Java实现这五种排序算法的示例代码:
- 冒泡排序(Bubble Sort):
javaCopy code
publicclassBubbleSort { publicstaticvoidbubbleSort(int[] arr) { intn= arr.length; for (inti=0; i < n - 1; i++) { for (intj=0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // 交换位置 inttemp= arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }
- 选择排序(Selection Sort):
javaCopy code
publicclassSelectionSort { publicstaticvoidselectionSort(int[] arr) { intn= arr.length; for (inti=0; i < n - 1; i++) { intminIndex= i; for (intj= i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } // 交换位置 inttemp= arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } }
- 插入排序(Insertion Sort):
javaCopy code
publicclassInsertionSort { publicstaticvoidinsertionSort(int[] arr) { intn= arr.length; for (inti=1; i < n; i++) { intkey= arr[i]; intj= i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } }
- 归并排序(Merge Sort):
javaCopy code
publicclassMergeSort { publicstaticvoidmergeSort(int[] arr, int left, int right) { if (left < right) { intmid= (left + right) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } } publicstaticvoidmerge(int[] arr, int left, int mid, int right) { intn1= mid - left + 1; intn2= right - mid; int[] L = newint[n1]; int[] R = newint[n2]; for (inti=0; i < n1; i++) { L[i] = arr[left + i]; } for (intj=0; j < n2; j++) { R[j] = arr[mid + 1 + j]; } inti=0, j = 0, k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } }
- 快速排序(Quick Sort):
javaCopy code
publicclassQuickSort { publicstaticvoidquickSort(int[] arr, int low, int high) { if (low < high) { intpi= partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } publicstaticintpartition(int[] arr, int low, int high) { intpivot= arr[high]; inti= low - 1; for (intj= low; j < high; j++) { if (arr[j] < pivot) { i++; // 交换位置 inttemp= arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // 将pivot放到正确的位置 inttemp= arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } }
这五种排序算法分别是冒泡排序、选择排序、插入排序、归并排序和快速排序,在不同的场景下有不同的适用性。在实际应用中,我们可以根据数据规模和性能需求选择合适的排序算法。