给定一个长度为 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;
}