快速排序(递归形式,随机选取基准)

    快速排序的运行时间与划分是否对称有关,其最坏情况发生在划分过程产生的两个区域分别包含n-1个元素和1个元素的时候。

由于的数partition的每步计算时间为O(n),所以如果算法Prition的每步都出现这种不对称划分,则其计算时间复杂性T(n)满足
             O(1)  n≤1
T(n)={  T(n- 1)+0(n)  n>1     解此递归方程,可得T(n)=O(n^2)


在最好情况下,每次划分所取的基准都恰好为中值即每次划分都产生两个大小为n/2的区域,此时,Partition 算法的计算时间T(n)

满足
               O(1)   n≤1
T(n)=      2T(n/2)+ O(n)   n>1其解为T(n)=O(nlogn)


可以证明, 快速排序算法在 平均情况下的时间复杂性 也是 O(nlogn)

 

产生指定范围的随机数:

int ranNumber =random.nextInt(max - min + 1) + min; // ranNumber 将被赋值为一个 min 和 max 范围内的随机数[min,max]

 

import java.util.Random;
import java.util.Scanner;

public class main6 {
	static final int max=105;
	public static int Partition(int a[],int p,int r){
		 int i=p,j=r+1;
		 int x=a[p];    //选基准
		 //将小于x的元素交换到左边区域,将大于x的元素交换到右边区域
		 while(true){
			 while(a[++i]<x&&i<r);
			 while(a[--j]>x);
			 if(i>=j) 
				 break;
			 int t=0;
			 t=a[i];
			 a[i]=a[j];
			 a[j]=t;
		 }
		 a[p]=a[j];
		 a[j]=x;
		 return j;
	}
	public static int RandomPartition(int a[],int p,int r){     //随机选取基准
		  Random random=new Random();
		  int i=random.nextInt(r-p+1)+p;
		  int t=a[i];
		  a[i]=a[p];
		  a[p]=t;
		  return Partition(a,p,r);
	}
   public static void QuickSort(int a[],int p,int r){              //递归
		if(p<r){
			int q=RandomPartition(a,p,r);
			QuickSort(a,p,q-1);//对左半段排序
			QuickSort(a,q+1,r);//对右半段排序
		}
	}
    public static void main(String[] args) {
		 Scanner scan=new Scanner(System.in);
		 int n=scan.nextInt();
		 int a[]=new int[max];
		 for(int i=0;i<n;i++){
			 a[i]=scan.nextInt();
		 }
		 QuickSort(a,0,n-1);
		 for(int i=0;i<n;i++){
			 System.out.print(a[i]+" ");
		 }
		 System.out.println();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ksuper&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值