Java实现排序

1.快速排序

class Solution {
    public int[] sortArray(int[] nums) {
        int l = 0;
        int h = nums.length-1;
        quickSort(nums, l, h);
        return nums;

    }
    //一趟快速排序
    int partion (int[] nums, int l, int h){
        int pivot = nums[l];
        while(l < h){
            while(l < h && nums[h] >= pivot) --h;
            swap(nums, l ,h);
            while(l < h && nums[l] <= pivot) ++l;
            swap(nums, l ,h);  
        }
        return l;
    }
    //递归实现快速排序算法
    void quickSort(int[] nums, int l, int h){
        if(l < h){
            int pivotloc = partion(nums, l, h);
            quickSort(nums, l, pivotloc-1);
            quickSort(nums, pivotloc+1, h);
        }
    }
    //交换数组元素的函数
    void swap(int[] nums, int l , int h){
        int temp = nums[l];
        nums[l] = nums[h];
        nums[h] = temp;
    }
    /*注意下面代码无法实现数组元素交换。因为形参的不直接影响实参的值。这种方法只是交换了两个形参的值,对实参并没有影响。上面的方法是因为传入的参数实际上是地址,改变了地址中的值所以数组也就变了。
    void swap(int x, int y){
        int temp = 0;
        temp = x;            
        x = y;
        y = temp;
    }
    */
}
  1. 插入排序
class Solution {
    public int[] sortArray(int[] nums) {
        insertSort(nums);
        return nums;
    }
    void insertSort(int[] nums){
        for (int i = 1; i< nums.length; i++){
            int r = nums[i];
            for (int j = i - 1; j >= 0; j--){
                if(r < nums[j]){
                    nums[j+1] = nums[j];
                    nums[j] = r;
                }else{
                    break;
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值