912 排序数组

5 篇文章 0 订阅
4 篇文章 0 订阅

题目:给你一个整数数组 nums,请你将该数组升序排列。

详细要求见LeetCode912

方法一:快速排序

快速排序原理:

1.选定中心轴数

2.将比中心轴数小的数放在中心轴的左边,构成左子数组,比中心轴大的数放在中心轴右边,构成右子数组

3.左子数组、右子数组重复上述操作

class Solution {
    public int[] sortArray(int[] nums) {
                 QuickSort(nums,0,nums.length-1);
                 return nums;
            }
    
  public void QuickSort(int[] nums,int start,int end){
        int index=Partition(nums,start,end);//获得中心轴数下标
        if(start==end)
         return;
        if(start<index){
             QuickSort(nums,start,index-1);//对左子数组排序
             }
          if(index<end){
             QuickSort(nums,index+1,end);//对右子数组排序
         }
         }
    
   public int Partition(int[] nums,int start,int end){
       int index=(int)(Math.random()*(end-start+1)+start);//随机确定中心轴
        swap(nums,index,end);//将中心轴数移到最后
        int small=start-1;
        for(index=start;index<end;index++){
          
            if(nums[index]<=nums[end]){
                 small++;
                 if(small!=index)
                  swap(nums,index,small);
            }
        }
        small++;
        swap(nums,small,end);//将中心轴数插入到左子数组后
        return small;
    }
      private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}

说明:

  • Partition函数返回左子数组后的第一个数的下标,即中心轴数的下标

  • java 中不能直接使用swap交换函数,因为java只有值传递,故重写swap方法,通过传数组的方法实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容与0801

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值