ITeye博客

[ J2SE ] 快速排序

jamour · 2007-06-09 10:31 · Markdown

public class QuitSort {
 int a[] = { 100, 40, 60, 87, 34, 11, 56, 0 };

 public void sort(int[] a, int i, int j) {
  int p = 0;
  if (i < j) {
   p = partition(a, i, j);//划分
   sort(a, i, p - 1);//对左区间递归排序
   sort(a, p + 1, j);//对右区间递归排序
  }
 
 }

 // 将数组进行划分 
 public int partition(int[] b, int low, int high) {
  int controlKey = b[low];
  while (low < high) {
   //   100, 40, 60, 87, 34, 11, 56, 0,[100]
   while ((low < high) && b[high] >= controlKey)
    high--;//从右向左扫描,查找第1个关键字小于controlKey的记录b[high]
   if (low < high)
    b[low++] = b[high];
   while (low < high && b[low] <= controlKey)
    low++;//从左向右扫描,查找第1个关键字大于control的记录b[low]
   if (low < high)
    b[high--] = b[low];
  }
  b[low] = controlKey;
  return low;//返回基准记录
 }

 public void print() {
  for (int q = 0; q < a.length; q++) {
   System.out.print(a[q]+",");
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub  
  QuitSort quitSort = new QuitSort();
  quitSort.sort(quitSort.a, 0, quitSort.a.length - 1);
  quitSort.print();
 }

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。