排序算法模板(java)

1 快速排序

public class Solution {
    public void sort(int[] nums){
        if (nums == null || nums.length == 0) return;
        quickSort(nums, 0, nums.legnth-1)
    }

    private void quickSort(int[] nums, int start ,int end ) {
        if(start >= end) return ;
        int left = start, right= end;
        // 枢轴 get value not index
        int pivot = nums[(left + right )/2];

        while (left <= right){
            while (left<= right && nums[left] < pivot){
                left ++;
            }
            while ( left <= right && nums[right] > pivot){
                right--;
            } 
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left ++;
                right --;
            }
        }

        quickSort(nums[], start, right);
        quickSort(nums[], left, end);
    }
}

2 归并排序

public class Solution {
    public void sort(int[] nums){
        if (nums == null || nums.length == 0) return;
        int[] temp = new int [nums.length];
        mergeSort(nums, 0, nums.legnth - 1, temp);
    }
   //分
    private void mergeSort(int[] nums, int start, int end, int[] temp){
        if(start >= end ) return ;

        mergeSort(nums, start, (start + end)/2, temp);
        mergeSort(nums, (start + end)/2+1, end, temp);
        merge(nums, start, end, temp);
    }
    //合
    private void merge(int[] nums, int start,  int end , int[] temp){
        int mid = (start + end)/2;
        int leftIndex = start;
        int rightIndex= mid + 1;
        int index = leftIndex;

        while(leftIndex <= mid && rightIndex <= end){
            if(nums[leftIndex] < nums[rightIndex]){
                temp[index++] = nums[leftIndex++];
            }
            else{
                temp[index++] = nums[rightIndex++];
            }
        }

        while(leftIndex <= mid){
           temp[index++] = nums[leftIndex++];
       }
        while(rightIndex <= end){
           temp[index++] = nums[rigghtIndex++];
       }
        for(int i=0; i<end;i++){
            nums[i] = temp[i];
        }
    }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值