java快速排序的代码
时间: 2023-10-12 07:09:33 浏览: 30
好的,以下是 Java 快速排序的代码:
```
public static void quickSort(int[] nums, int left, int right) {
if(left >= right) {
return;
}
int pivot = nums[left];
int i = left, j = right;
while(i < j) {
while(i < j && nums[j] >= pivot) {
j--;
}
nums[i] = nums[j];
while(i < j && nums[i] < pivot) {
i++;
}
nums[j] = nums[i];
}
nums[i] = pivot;
quickSort(nums, left, i - 1);
quickSort(nums, i + 1, right);
}
```
希望能对您有所帮助。还有什么问题吗?
相关问题
java快速排序代码
Java快速排序的代码实现如下:
```
public class QuickSort {
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int index = partition(arr, left, right);
quickSort(arr, left, index - 1);
quickSort(arr, index + 1, right);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[left];
while (left < right) {
while (left < right && arr[right] >= pivot) {
right--;
}
arr[left] = arr[right];
while (left < right && arr[left] <= pivot) {
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}
public static void main(String[] args) {
int[] arr = {5, 2, 9, 4, 7, 6, 1, 3, 8};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
}
```
该代码使用了递归的思想实现了快速排序,其中 `quickSort()` 方法用于递归调用 `partition()` 方法,对左右两边的子数组进行排序。`partition()` 方法则是用于分区的,它通过选定一个基准元素(pivot),将数组分成小于基准的部分和大于基准的部分,并返回基准元素所在的下标。最后,通过不断递归调用 `quickSort()` 方法,直到整个数组有序。
java 快速排序代码
以下是Java实现快速排序的代码:
```
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
}
```
这段代码实现了快速排序的核心思想,即通过选取一个pivot,将数组分为两部分,一部分比pivot小,一部分比pivot大,然后对这两部分分别进行递归排序,最终得到有序数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)