java的排序算法,代码详细说明
Java中常见的排序算法有以下几种:
- 冒泡排序(Bubble Sort):
java
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (array[j] > array[j+1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
- 选择排序(Selection Sort):
java
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
- 插入排序(Insertion Sort):
java
public static void insertionSort(int[] array) {
int n = array.length;
for (int i = 1; i < n; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j+1] = array[j];
j--;
}
array[j+1] = key;
}
}
- 快速排序(Quick Sort):
java
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
public static int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i+1];
array[i+1] = array[high];
array[high] = temp;
return i + 1;
}
- 归并排序(Merge Sort):
java
public static void mergeSort(int[] array, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(array, low, mid);
mergeSort(array, mid + 1, high);
merge(array, low, mid, high);
}
}
public static void merge(int[] array, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low, j = mid+1, k = 0;
while (i <= mid && j <= high) {
if (array[i] <= array[j]) {
temp[k++] = array[i++];
} else {
temp[k++] = array[j++];
}
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= high) {
temp[k++] = array[j++];
}
for (int index = 0; index < temp.length; index++) {
array[low + index] = temp[index];
}
}
这些是Java中常见的排序算法,每个算法都有其优缺点,适用于不同的场景和数据规模。例如,冒泡排序和选择排序适用于小数据规模,快速排序和归并排序适用于大数据规模。