Java中的经典排序算法:插入排序、希尔排序、选择排序、堆排序与冒泡排序(如果想知道Java中有关插入排序、希尔排序、选择排序、堆排序与冒泡排序的知识点,那么只看这一篇就足够了!)
以下是Java中经典排序算法的实现代码:
插入排序:
public void insertionSort(int[] arr) {
int i, j, key;
for (i = 1; i < arr.length; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
希尔排序:
public void shellSort(int[] arr) {
int i, j, inc;
for (inc = arr.length / 2; inc > 0; inc /= 2) {
for (i = inc; i < arr.length; i++) {
int key = arr[i];
j = i;
while (j >= inc && arr[j - inc] > key) {
arr[j] = arr[j - inc];
j -= inc;
}
arr[j] = key;
}
}
}
选择排序:
public void selectionSort(int[] arr) {
int i, j, min_idx;
for (i = 0; i < arr.length - 1; i++) {
min_idx = i;
for (j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
堆排序:
public void heapSort(int[] arr) {
for (int i = arr.length / 2 - 1; i >= 0; i--) {
heapify(arr, arr.length, i);
}
for (int i = arr.length - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// heapify root element
heapify(arr, i, 0);
}
}
private void heapify(int[] arr, int n, int i) {
int largest = i;
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest]) {
largest = l;
}
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest]) {
largest = r;
}
// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
冒泡排序:
public void bubbleSort(int[] arr) {
int i, j;
boolean swapped;
int n = arr.length;
for (i = 0; i < n - 1; i
评论已关闭