快速排序算法2

来源:互联网 发布:怎么淘宝做考试用书 编辑:程序博客网 时间:2024/04/27 14:14

package com.mianshi;

/**
 * describe: 快速排序算法2(排序结果从小到大)
 * create on: 2011-05-25
 * @author sylor.liu
 * @version 1.0
 * @since jdk1.6
 */
public class QuickSort2 {
 
 
 private void swap(int a[], int x, int y){
  int temp = a[x];
  a[x] = a[y];
  a[y] = temp;
 }
 
 // 对数据进行快速排序
 private void qsort(int a[], int low,int high){
  
  // 将该段数据的第一个值a[low]设为基准值
  int point = a[low];
  int left = low + 1;
  int right = high;
  
  if(low == high){
   return;
  }
  
  if(high - low ==1 ){
   if(a[high] < a[low]){
    swap(a,high,low);
   }
   return;
  }
  
  // 将该段数据的值进行互换,使左边的值小于point 右边的值大于point 且a[left-1]从左边起第一个大于point值
  while(left < right){
   while(left < right&& left < high){
    if(a[left] > point){
     break;
    }
    left++;
   }
   
   while(left < right&& right > low){
    if(a[right] < point){
     break;
    }
    right--;
   }
   swap(a,left,right);
  }
  
  // 左边起第一个大于point值a[left-1] 与a[low]互换
  swap(a,low,left-1);
  
  // 对左半段排序
  qsort(a,low,left-1);
  
  // 对右半段排序
  qsort(a,left ,high);

 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
        int a[] = new int[]{12,2,9,5,67,32,6,7,33};
        QuickSort2 qs = new QuickSort2();
        qs.qsort(a,0,a.length - 1);
       
        for (int i = 0; i < a.length; i++) {
   System.out.print(a[i] + " ;");
  }
        System.out.println();
 
 }
   
}

原创粉丝点击