Java中常见的排序算法包括以下几种:
public void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // 交换位置 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
public void selectionSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } // 交换位置 int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } }
public void insertionSort(int[] arr) { int n = arr.length; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } }
public void quickSort(int[] arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); quickSort(arr, low, pivotIndex - 1); quickSort(arr, pivotIndex + 1, high); } } private int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; // 交换位置 int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // 交换位置 int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr j + 1] = temp; return i + 1; }
```java public void mergeSort(int[] arr, int low, int high) { if (low < high) { int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } } private void merge(int[] arr, int low, int mid, int high) { int n1 = mid - low + 1; int n2 = high - mid; int[] leftArr = new int[n1]; int[] rightArr = new int[n2]; for (int i = 0; i < n1; i++) { leftArr[i] = arr[low + i]; } for (int j = 0; j < n2; j++) { rightArr[j] = arr[mid + 1 + j]; } int i = 0, j = 0, k = low; while (i < n1 && j < n2) { if (leftArr[i] <= rightArr[j]) { arr[k] = leftArr[i]; i++; } else { arr[k] = rightArr[j]; j++; } k++; } while (i < n1) { arr[k] = leftArr[i]; i++; k++; } while (j < n2) { arr[k] = rightArr[j]; j++; k++; } }
这些是Java中常见的排序算法,每个算法都有其适用的场景和性能特点。可以根据具体的需求选择合适的排序算法。
原文链接:codingdict.net