java的快速排序代码怎么写
时间: 2023-09-16 17:05:54 浏览: 54
### 回答1:
Java的快速排序是一种分治算法,它将一个数组分成两个部分,左边的部分包含比基准值小的元素,右边的部分包含比基准值大的元素。代码如下:
public static void quickSort(int[] arr,int low,int high){
int i,j,temp,t;
if(low>high){
return;
}
i=low;
j=high;
//temp就是基准位
temp = arr[low]; while (i<j) {
//先看右边,依次往左递减
while (temp<=arr[j]&&i<j) {
j--;
}
//再看左边,依次往右递增
while (temp>=arr[i]&&i<j) {
i++;
}
//如果满足条件则交换
if (i<j) {
t = arr[j];
arr[j] = arr[i];
arr[i] = t;
} }
//最后将基准为与i和j相等位置的数字交换
arr[low] = arr[i];
arr[i] = temp;
//递归调用左半数组
quickSort(arr, low, j-1);
//递归调用右半数组
quickSort(arr, j+1, high);
}
### 回答2:
快速排序是一种常用的排序算法,可以通过递归的方式对一个数组进行排序。以下是一种常见的Java实现:
```java
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // 选择最后一个元素作为基准值
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {5, 3, 1, 6, 2, 4};
int n = arr.length;
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
```
在快速排序中,我们选择一个元素作为基准值,将小于基准值的元素放到基准值左边,将大于基准值的元素放到基准值右边,然后递归地对左右两个子数组进行排序,直到整个数组有序。这里使用的是最后一个元素作为基准值,通过双指针的方式,将小于基准值的元素交换到前面,大于基准值的元素交换到后面。
在示例代码中,我们对数组 {5, 3, 1, 6, 2, 4} 进行排序,输出结果为 {1, 2, 3, 4, 5, 6}。
### 回答3:
快速排序是一种常用的排序算法,它的基本思想是通过递归地将数组划分为较小和较大的两个子数组,然后对子数组进行排序,最后将排好序的子数组合并,从而得到整个数组排好序的结果。
以下是用Java实现快速排序的代码:
```java
public class QuickSort {
public static void main(String[] args) {
int[] arr = {5, 9, 3, 1, 8, 6, 2, 7, 4};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; 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[high];
arr[high] = temp;
return i + 1;
}
}
```
以上代码中,首先定义了一个`quickSort`函数用于递归地进行快速排序。在`quickSort`函数中,通过调用`partition`函数来实现数组划分和交换元素的操作。`partition`函数选择数组的最后一个元素作为基准元素`pivot`,然后遍历数组,将小于等于`pivot`的元素放到左边,大于`pivot`的元素放到右边。最后,将`pivot`元素放到正确的位置上,并返回该位置的索引。
在`main`函数中,我们定义了一个数组`arr`作为示例输入,并调用`quickSort`函数进行排序。最后,打印排序后的结果。
快速排序的时间复杂度为O(nlogn),其中n为待排序数组的长度。它是一种高效的排序算法,在实际中被广泛应用。