- //修改后的代码
- public class QuickSortDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int[] a = {12,2,66,9,27,15,91,83,3,10};
- quickSort(a,0,a.length-1);
- for(int i=0;i<a.length;i++){
- System.out.print(a[i] + " ");
- }
- }
- public static int getMiddle(int[] arr, int low, int high){
- int temp = arr[low];
- while (low < high) {
- while (low < high && temp <= arr[high]){
- high--;
- }
- if(low<high) //我感觉这个地方得判断一下
- {
- arr[low] = arr[high];
- }
- //小于中轴值的放到前面
- while(low < high && temp >= arr[low]){
- low++;
- }
- if(low<high) //还有这个地方也应该判断一下
- arr[high] = arr[low]; //大于中轴值的放到后面
- }
- arr[low] = temp;
- return low;
- }
- /*
- public static void quickSort(int[] arr,int low,int high){
- while(low < high){//问题出现在这里,这里不应该用循环语句,在这里出现了死循环
- int middle = getMiddle(arr, low, high);
- quickSort(arr, low, middle-1); //小于中轴值的前半部分
- quickSort(arr, middle+1, high); //大于中轴值的后半部分
- }
- }
- */
- /*
- 下面是正确的函数
- */
- public static void quickSort(int[] arr,int low,int high){
- if(low < high)
- {
- int middle = getMiddle(arr, low, high);
- quickSort(arr, low, middle-1); //小于中轴值的前半部分
- quickSort(arr, middle+1, high); //大于中轴值的后半部分
- }
-
- }
- }
复制代码 |