1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| 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){
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); } } } ```<font color=#008000> output:0 2 2 0 0 4 5 0 0 0 0 为什么会这样那,因为有重复的值,在交换时出现了相当于:
a=a^a;
a=a^a;
a=a^a;
的操作,结果就变成0了。
以下是正确食用方法:</font>
```java 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;
} 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); } } }
|