java快速排序代码怎么写
时间: 2023-09-19 11:06:11 浏览: 54
### 回答1:
Java快速排序的代码如下:
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10,7,8,9,1,5};
quickSort(arr, 0, arr.length-1);
for(int i=0; i<arr.length; i++){
System.out.print(arr[i]+" ");
}
}
public static void quickSort(int[] arr, int low, int high){
if(arr==null || arr.length==0)
return;
if(low>=high)
return;
//pick the pivot
int middle = low + (high-low)/2;
int pivot = arr[middle];
//make left < pivot and right > pivot
int i = low, j = high;
while(i<=j){
while(arr[i]<pivot){
i++;
}
while(arr[j]>pivot){
j--;
}
if(i<=j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
//recursively sort two sub parts
if(low<j)
quickSort(arr, low, j);
if(high>i)
quickSort(arr, i, high);
}
}
### 回答2:
Java中的快速排序算法可以通过递归实现。它的基本思想是选择一个元素作为基准值,将其它元素分割为小于基准值和大于基准值的两部分,然后对这两部分进行递归排序。
下面是一个示例的快速排序代码实现:
```java
public class QuickSort {
public static void main(String[] args) {
int[] array = {5, 9, 2, 4, 7, 1, 8, 6, 3};
quickSort(array, 0, array.length - 1);
System.out.println("排序结果:");
for (int num : array) {
System.out.print(num + " ");
}
}
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
public static int partition(int[] array, int low, int high) {
int pivot = array[low];
while (low < high) {
while (low < high && array[high] >= pivot) {
high--;
}
array[low] = array[high];
while (low < high && array[low] <= pivot) {
low++;
}
array[high] = array[low];
}
array[low] = pivot;
return low;
}
}
```
以上代码实现了一个快速排序算法。它首先选择数组的第一个元素作为基准值,然后通过partition函数将其它元素分割为小于基准值和大于基准值的两部分。然后对这两部分分别进行递归排序。最终得到一个有序数组。
在运行上述代码后,将会输出排序结果。在本例中,输出结果为1 2 3 4 5 6 7 8 9,表示数组已经按照从小到大的顺序排序。
### 回答3:
Java中快速排序的代码可以使用递归的方式来实现。下面是一种常用的实现方法:
```java
public class QuickSort {
public static void main(String[] args) {
int[] nums = {5, 2, 8, 1, 9, 4, 3};
quickSort(nums, 0, nums.length - 1);
System.out.println("排序后的数组:");
for (int num : nums) {
System.out.print(num + " ");
}
}
public static void quickSort(int[] nums, int low, int high) {
if (low < high) {
int pivot = partition(nums, low, high);
quickSort(nums, low, pivot - 1);
quickSort(nums, pivot + 1, high);
}
}
public static int partition(int[] nums, int low, int high) {
int pivot = nums[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (nums[j] <= pivot) {
i++;
swap(nums, i, j);
}
}
swap(nums, i + 1, high);
return i + 1;
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
```
上述代码定义了一个`QuickSort`类,其中`main`函数用于测试。`quickSort`函数是递归的主要排序函数,接受一个整数数组`nums`和待排序子数组的上下界`low`和`high`作为参数。
在`quickSort`函数中,首先判断`low`是否小于`high`,如果满足,则调用`partition`函数将数组划分成左右两部分,再分别对左右两部分进行快速排序,直至子数组的长度为1时结束递归。
`partition`函数用于将数组划分成两部分,左部分小于等于基准值,右部分大于基准值。它从左到右遍历数组,将小于等于基准值的元素交换到左侧,最后将基准值放到正确的位置上,并返回该位置。
`swap`函数用于交换数组中两个位置的元素。
以上是一种常见的快速排序实现方法,可以根据实际情况进行修改和优化。