public static void quickSort(int[] a,int l,int r){
if (l<r){
int temp=a[l];
while (l<r){
while (l<r && a[r]>temp){
r--;
}
if (l<r){
a[l++]=a[r];
}
while (l<r && a[l]<=temp){
l++;
}
if (l<r){
a[r--]=a[l];
}
}
a[l]=temp;
quickSort(a,l,temp-1);
quickSort(a,temp+1,r);
}
}
public static void main(String[] args){
int[] a = {6,7,2,4,7,62,3,4,2,1,8,9,19};
quickSort(a, 0, a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
public class Quicksort {
public static void main(String[] args) {
int[] a = {6, 7, 2, 4, 7, 62, 3, 4, 2, 1, 8, 9, 19};
new Quicksort().sort(a,0,a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
public void sort(int[] nums, int start, int end) {
if (end > start) {
int pivot = partition(nums, start, end);
sort(nums, start, pivot - 1);
sort(nums, pivot + 1, end);
}
}
private int partition(int[] nums, int start, int end) {
//随机选择一个值作为中间值
int random = new Random().nextInt(end - start + 1) + start;
//将改值交换到尾部
swap(nums, random, end);
//small指针初始化为-1,
int small = start - 1;
//向后遍历
for (int i = start; i < end; i++) {
//如果发现存在小于中间值的数字
if (nums[i] < nums[end]) {
//small向右移动一格
small++;
//small和当前数字进行交换
swap(nums, i, small);
}
}
//如果没有找则small放回原位置
small++;
swap(nums, small, end);
return small;
}
private void swap(int[] nums, int index1, int index2) {
if (index1 != index2) {
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
}
}
你最后quickSort(a,l,temp-1); quickSort(a,temp+1,r); 不能用l和r,因为你之前已经自增自减了,你得在前面定义一个临时变量存储了l,r。
其次你这个【quickSort(a,l,temp-1)】咋是用temp做中间下标啊!!!!
帮你改了一下:
public static void quickSort(int[] a,int l,int r){
if (l<r){
int s = l,e = r; //临时存储l,r
int temp=a[l];
while (l<r){
while (l<r && a[r]>temp ){
r--;
}
if (l<r ){
a[l++]=a[r];
}
while (l<r && a[l]<=temp ){
l++;
}
if (l<r ){
a[r--]=a[l];
}
}
a[l]=temp;
quickSort(a,s,l-1); //修改temp
quickSort(a,l+1,e); //修改temp
}
}
public static void main(String[] args){
int[] a = {6,7,2,4,7,62,3,4,2,1,8,9,19};
quickSort(a, 0, a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}