在Java中,你可以使用`java.util.Arrays`类提供的`sort()`方法来对数组进行排序。下面是一些常见的排序方法及其实现:
快速排序
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr = {4, 3, 5, 1, 7, 9, 3};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int begin, int end) {
if (end <= begin) return;
int partitionIndex = partition(arr, begin, end);
quickSort(arr, begin, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, end);
}
private static int partition(int[] arr, int begin, int end) {
int pivot = arr[end];
int i = begin - 1;
for (int j = begin; j < end; 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[end];
arr[end] = temp;
return i + 1;
}
}
冒泡排序
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {4, 3, 5, 1, 7, 9, 3};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static 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 class SelectionSort {
public static void main(String[] args) {
int[] arr = {4, 3, 5, 1, 7, 9, 3};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
public static 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 class InsertionSort {
public static void main(String[] args) {
int[] arr = {4, 3, 5, 1, 7, 9, 3};
insertionSort(arr);
System.out.println(Arrays.toString(arr));
}
public static 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 = j - 1;
}
arr[j + 1] = key;
}
}
}
以上代码展示了如何使用Java实现几种常见的排序算法。