日期:2014-05-20  浏览次数:20742 次

一个快速排序的小程序,求解错误!
看了书上的快速排序后自己就试着编写了一个小程序,编译的时候没查出错误来,求能人看下错在哪里啊!

public class TestArray {
  public static void main(String[] args) {
  int[] arr = {23, 34, 5, 98, 20, 7, 200};
  quickSort(arr, 0, arr.length-1);  
  for(int i = 0; i <arr.length; i++)
  System.out.print(arr[i]+" ");  
  }

  public static int partition(int[] arr, int low, int high) {
  int qivotkey = arr[low];

  while(low < high) {
  while(low < high && arr[high] >= qivotkey) high--;
  arr[low] = arr[high];
  while(low < high && arr[low] <=qivotkey) low++;



  arr[high] = arr[low];
  }
  arr[low] = qivotkey;
  return low;
  }

  public static void quickSort(int[] arr, int low, int high) { 
  if(low < high) {  
  int qivotloc = partition(arr, low, high);  
  quickSort(arr, low, qivotloc-1);
  quickSort(arr, qivotloc+1, high);
  }
  }
}

------解决方案--------------------
Java code

while(low < high) {
  while(low < high && arr[high] >= qivotkey) high--;
  arr[low] = arr[high];  // 这句有问题
  while(low < high && arr[low] <=qivotkey) low++;
  arr[high] = arr[low];  // 这句也是,楼主并没有交换a[low]和a[high]的值
}