冒泡排序(Bubble Sort)和快速排序(Quick Sort)是两种常见的排序算法。以下是用Java实现的代码示例:
冒泡排序:
public class BubbleSort {
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]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {
64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序结果:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
快速排序:
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi+1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // 选取最后一个元素作为pivot
int i = low-1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
// 交换arr[i]和arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// 交换arr[i+1]和arr[high]
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
public static void main(String[] args) {
int[] arr = {
64, 34, 25, 12, 22, 11, 90};
int n = arr.length;
quickSort(arr, 0, n-1);
System.out.println("排序结果:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
以上是用Java实现的冒泡排序和快速排序算法。你可以通过调用bubbleSort
和quickSort
方法来排序一个整数数组。