牛客网排序题-快排

给定一个长度为 n 的数组,请你编写一个函数,返回该数组排序后的结果。

数据范围:0<=n<=10 0000 ,数组中每个元素都满足 

要求:空间复杂度 O(n),时间复杂度 

用快排

 我写的快排(超时了)

public int[] MySort (int[] arr) {
        quickSort(arr,0,arr.length-1);
        return arr;
    }
    public void quickSort(int[] arr,int low,int high){
         if(low>=high) return;
        int left = low;
        int right = high;
        int pivot = arr[low];
        while(low<high){
            while(low<high && arr[high]>pivot){
                high--;
            }
            if(low<high) arr[low] = arr[high];
            while(low<high && arr[low]<pivot){
                low++;
            }
            if(low<high) arr[high] = arr[low];
        }
        arr[low] = pivot;
        quickSort(arr,left,low-1);
        quickSort(arr,low+1,right);
    }
import java.util.*;


public class Solution {
    public int[] MySort (int[] arr) {
        quickSort(arr,0,arr.length-1);
        return arr;
    }
    public void quickSort(int[] arr,int left,int right){
         if (left < right) {
            int partitionIndex = partition(arr, left, right);
            quickSort(arr, left, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, right);
        }
    }
     private static int partition(int[] arr, int left, int right) {
        // 设定基准值(pivot)
        int pivot = left;
        int index = pivot + 1;
        for (int i = index; i <= right; i++) {
            if (arr[i] < arr[pivot]) {
                swap(arr, i, index);
                index++;
            }
        }
        swap(arr, pivot, index - 1);
        return index - 1;
    }
 
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

上面第二个是网上看到的别人顺利通过的答案

下面是自己写的,第一个版本没过的原因就是没有好好理解快排本身的思想,加了没用的while,实际上和谁交换不重要,最后都能得到正确的结果

public void quickSort(int[] arr,int low,int high){
        if(low>=high) return;
        int left = low;
        int right = high;
        int pivot = arr[low];
        low++;
        while(low<=high){
            if(arr[low]<pivot) low++;
            else {
                swap(arr,low,high);
                high--;
            }
        }
        swap(arr,left,low-1);
        quickSort(arr,left,low-2);
        quickSort(arr,low,right);
    }
    public void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值