排序算法之快速排序

package com.lin.sort;
/** 
 * @version 创建时间:2016-8-12 下午02:42:05 
 * 类说明 :快速排序法(Quick Sort)
 * 
 * 快速排序的最坏时间复杂度为O(n^2).
 * 快速排序所占用的辅助空间为递归时所需栈的深度,故空间复杂度为O(log2(n))。同时,快速排序是不稳定的排序。
 */
public class QuickSort {

	public void swap(int a[],int i,int j){
		int temp=a[i];
		a[i]=a[j];
		a[j]=temp;
	}
	
	public int partSort(int a[],int low,int high){
		int pivot,p_pos,i;
		p_pos=low;
		pivot=a[p_pos];
		for(i=low+1;i<=high;i++){
			if(a[i]>pivot){
				p_pos++;
				swap(a, p_pos, i);
			}
		}
		swap(a, low, p_pos);
		return p_pos;
	}
	
	public void quicksort(int a[],int low,int high){
		int pivot;
		if(low<high){
			pivot=partSort(a, low, high);
			quicksort(a, low, pivot-1);
			quicksort(a, pivot+1, high);
		}
	}
	
	public static void main(String[] args) {
		// 快速排序法(Quick Sort)
		int vec[] = new int[] { 37, 46, 33, -5, 17, 51 };
		QuickSort s = new QuickSort();
		long begin = System.currentTimeMillis();
		for (int k = 0; k < vec.length; k++) {
			s.quicksort(vec, 0, vec.length-1);
		}
		long end = System.currentTimeMillis();
		System.out.println("快速法用时为:" + (end - begin));
		// 打印排序好的结果
		for (int i = 0; i < vec.length; i++) {
			System.out.print(vec[i]+" ");
		}
	}
}

测试结果:

快速法用时为:0
51 46 37 33 17 -5 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Radom7

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

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

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

打赏作者

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

抵扣说明:

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

余额充值