牛客-java
题目描述
给定一个数组,请你编写一个函数,返回该数组排序后的形式。
快速排序,每次排序的时候都有一个基准点,将小于等于基准点的数放在基准点左边,将大于等于基准点的数全部放在右边。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 将给定数组排序
* @param arr int整型一维数组 待排序的数组
* @return int整型一维数组
*/
public int[] MySort (int[] arr) {
// write code here
if(arr.length == 0) return arr;
Qsort(arr,0,arr.length-1);
return arr;
}
void Qsort(int[] a,int left, int right){
if(left>=right) return;
int i,j,t,temp;
temp = a[left];//temp为基准数
i = left;
j = right;
while(i != j){
while (a[j] >= temp && i<j) j--;//先从右往左
while (a[i] <= temp && i<j) i++;//从左往右
if(i<j)//交换两个中间数的位置{
t = a[i];a[i]=a[j];a[j]=t;
}
}
a[left] = a[i];a[i]=temp;//最终将基准数归位
Qsort(a,left,i-1);//继续处理左边的
Qsort(a,i+1,right);//继续处理右边的,这里是递归的过程
}
}
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 将给定数组排序
* @param arr int整型一维数组 待排序的数组
* @return int整型一维数组
*/
public int[] MySort (int[] arr) {
// write code here
if(arr.length == 0) return arr;
Qsort(arr,0,arr.length-1);
return arr;
}
void Qsort(int[] a,int left, int right){
if(left>=right) return;
int i,j,t,temp;
temp = a[left];
i = left;
j = right;
while(i != j){
while (a[j] >= temp && i<j) j--;
while (a[i] <= temp && i<j) i++;
if(i<j){
t = a[i];a[i]=a[j];a[j]=t;
}
}
a[left] = a[i];a[i]=temp;
Qsort(a,left,i-1);
Qsort(a,i+1,right);
}
}