在Java中,要重新排列一个数组,你可以使用不同的排序算法,例如冒泡排序、选择排序、插入排序、快速排序等。下面是一些示例代码,展示了如何使用Java对数组进行重新排列:
冒泡排序
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {4, 3, 5, 1, 2, 9, 3, 0};
bubbleSort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
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]) {
// 交换 array[j] 和 array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
选择排序```javapublic class SelectionSort {
public static void main(String[] args) {
int[] array = {4, 3, 5, 1, 2, 9, 3, 0};
selectionSort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
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;
}
}
// 交换 array[minIndex] 和 array[i]
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
}
快速排序
```java
public class QuickSort {
public static void main(String[] args) {
int[] array = {4, 3, 5, 1, 2, 9, 3, 0};
quickSort(array, 0, array.length - 1);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 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++;
// 交换 array[i] 和 array[j]
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// 交换 array[i+1] 和 array[high]
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
}
随机重新排列数组

