JAVA实现快速排序(非递归)

这篇博客介绍了如何使用Java实现非递归的快速排序算法。通过创建栈来辅助排序过程,详细讲解了如何找到中轴位置并进行分区操作,最后提供了测试代码展示排序效果。

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

非递归实现时借助栈,

package sort;
import java.util.Stack;


public class Sort
{

/*

  * 非递归版本
  */
 public void quick2(int[] array){
 if (array == null || array.length == 1) return ;
 //存放开始与结束索引
 Stack<Integer> s = new Stack<Integer>(); 
 //压栈       
 s.push(0); 
 s.push(array.length - 1); 
 while (!s.empty()) { 
     int right = s.pop(); 
     int left = s.pop(); 
     //如果最大索引小于等于左边索引,说明结束了
     if (right <= left) continue; 
              
     int i = partition(array, left, right); 
     if (left < i - 1) {
         s.push(left);
         s.push(i - 1);
     } 
     if (i + 1 < right) {
         s.push(i+1);
         s.push(right);
     }

 } 

//*************找到中轴位置***********//

public int partition(int[] a,int start,int end)
 {
if (start<end)
{
int x = a[end];
int i = start-1;
for (int j = start; j < end; j++)
{
if (a[j]<=x)
{
i++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}else {
}
}
a[end] = a[i+1];
a[i+1] = x;
return i+1;//返回中轴位置
}
return 0;
}

//*********测试**********//

public static void main(String[] args)
{
int []a ={5,1,4,2,3};
Sort Sort = new Sort();
Sort.quick2(a);
for (int i : a)
{
System.out.println(i);
}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值