以下是错误代码:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
long []shu={1,2,4,3,5,2,432,5,32,41,2};
quickSort(shu,0,shu.length-1);
for(long a:shu){
System.out.print(a+" ");
}
}
public static void swap(long []shu,int a,int b){
/*long temp=shu[a];
shu[a]=shu[b];
shu[b]=temp;*/
shu[a]=shu[a]^shu[b];
shu[b]=shu[b]^shu[a];
shu[a]=shu[a]^shu[b];
}
public static int partition (long[]shu,int begin,int end){
long pivot =shu[end];
int storeindex=begin;
for(int i=begin;i<end;i++){
if(shu[i]<pivot){
swap(shu,i,storeindex);
storeindex++;
}
}
swap(shu,storeindex,end);
return storeindex;
}
public static void quickSort(long []shu,int begin,int end){
if(begin>=end){
return;
}
else{
int mid =partition(shu,begin,end);
quickSort(shu,begin,mid-1);
quickSort(shu,mid+1,end);
}
}
}
output:0 2 2 0 0 4 5 0 0 0 0
为什么会这样那,因为有重复的值,在交换时出现了相当于:
a=a^a;
a=a^a;
a=a^a;
的操作,结果就变成0了。
以下是正确食用方法:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
long []shu={1,2,4,3,5,2,432,5,32,41,2};
quickSort(shu,0,shu.length-1);
for(long a:shu){
System.out.print(a+" ");
}
}
public static void swap(long []shu,int a,int b){
long temp=shu[a];
shu[a]=shu[b];
shu[b]=temp;
/*shu[a]=shu[a]^shu[b];
shu[b]=shu[b]^shu[a];
shu[a]=shu[a]^shu[b];*/
}
public static int partition (long[]shu,int begin,int end){
long pivot =shu[end];
int storeindex=begin;
for(int i=begin;i<end;i++){
if(shu[i]<pivot){
swap(shu,i,storeindex);
storeindex++;
}
}
swap(shu,storeindex,end);
return storeindex;
}
public static void quickSort(long []shu,int begin,int end){
if(begin>=end){
return;
}
else{
int mid =partition(shu,begin,end);
quickSort(shu,begin,mid-1);
quickSort(shu,mid+1,end);
}
}
}