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
| private static void swap(int[] a,int l,int r){ if(l==r)return; a[l]=a[l]+a[r]; a[r]=a[l]-a[r]; a[l]=a[l]-a[r]; } public static void sort(int[] a,int l,int r){ if(l>=r)return; int k=partition(a, l, r); //swap(a, l, k); sort(a, l, k-1); sort(a, k+1, r); } public static int partition(int[] a,int l,int r){ int base=a[l]; while(l<r){ while(l<r&&a[r]>base){ r--; } while(l<r&&a[l]<base){ l++; } if(l<r) swap(a,l,r); } return l; } @Test public void testSwap(){ int[] a={1,2,3}; swap(a, 0, 2); System.out.println(StringUtils.join(ArrayUtils.toObject(a), ',')); } @Test public void testSort(){ int[] a={6,5,1,2,4,1,4,3,2,1}; sort(a, 0, a.length-1); System.out.println(StringUtils.join(ArrayUtils.toObject(a), ',')); Arrays.sort(a); System.out.println(StringUtils.join(ArrayUtils.toObject(a), ',')); }
|