- package net.itdos.csdn;
- public class QuickSort {
- public static void main(String[] args) {
- int[] nums = {657, 2334, 56, 87, 98, 87, 23, 576, 13, 2};
- sort(nums, 0, nums.length-1);
- for(int i = 0; i < nums.length; i++) {
- System.out.print(nums[i] + " ");
- }
- }
- static int partition(int[] nums, int low, int hight) {
- int pivot = nums[low]; //枢纽
- while(low < hight) {
- while(low < hight && pivot <= nums[hight]) { //从高位开始向前搜索
- hight--;
- }
- nums[low] = nums[hight];
- while(low < hight && pivot >= nums[low]) { //从低位开始向后搜索
- low++;
- }
- nums[hight] = nums[low];
- }
- nums[low] = pivot;
- return low;
- }
- /**
- * 递归
- */
- static void sort(int[] nums, int low, int hight) {
- if(low < hight) { //跳出递归的条件, 否则会 java.lang.StackOverflowError
- int pivot = partition(nums, low, hight);
- sort(nums, low, pivot-1);
- sort(nums, pivot + 1, hight);
- }
- }
- }
快速排序
最新推荐文章于 2024-09-12 15:56:42 发布