[ J2SE ] 快速排序

本文详细介绍了一种高效的排序算法——快速排序。通过递归的方式,利用分区操作将数组分为两个子数组,并分别对这两个子数组进行排序。文章展示了快速排序的具体实现代码,并解释了其工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值