数据结构--冒泡、快速排序

/**
 * 快速排序
 * @author neu_fufengrui@163.com
 *
 */
public class QuickSort {
	
	private QuickSort(){
		
	}
	
	/**
	 * 冒泡排序--下沉式气泡排序
	 * 时间复杂度O(n2)
	 * 空间复杂度O(1)
	 */
	public static void sort(int a[], int off, int len){
		for(int i = off; i < len; i++){
			for(int j = off; j < len-i; j++){
				if(a[j] > a[j+1]){
					swap(a, j, j+1);
				}
			}
			print(a);
		}
	}
	/*output ~.~
	11,12,5,31,30,26,34,36,18,38,
	11,5,12,30,26,31,34,18,36,38,
	5,11,12,26,30,31,18,34,36,38,
	5,11,12,26,30,18,31,34,36,38,
	5,11,12,26,18,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,

	 */
	/**
	 * 冒泡排序--上升时气泡排序
	 * 时间复杂度O(n2)
	 * 空间复杂度O(1)
	 */
	public static void sort1(int a[], int off, int len){
		for(int i = off; i < len; i++){
			for(int j = len; j > i; j--){
				if(a[j] < a[j-1]){
					swap(a, j, j-1);
				}
			}
			print(a);
		}
	}
	/*output ~.~
	5,11,31,12,18,34,30,26,38,36,
	5,11,12,31,18,26,34,30,36,38,
	5,11,12,18,31,26,30,34,36,38,
	5,11,12,18,26,31,30,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	5,11,12,18,26,30,31,34,36,38,
	 */
	/**
	 * 快速排序
	 * 通过一趟排序,将记录分成独立的两部分,其中一部分的关键字均比另一部分小,分别对两部分继续排序,达到整体有序的目的
	 * 与序列有关,平均时间复杂度:O(nlogn),最差退化为冒泡排序:O(n2)
	 * 空间复杂度:O(logn),一个栈空间
	 */
	public static void sort2(int a[], int low, int high){
		print(a);
		if(low < high){
			int mid = partition(a, low, high);//二分排序,并返回中间位置
			sort2(a, low, mid-1);//递归排序,小的部分
			sort2(a, mid+1, high);//递归排序,大的部分
		}
	}
	
	private static int partition(int a[], int low, int high){
		int temp = a[low];
		while(low < high){
			while(low < high && a[high] >= temp){
				high --;
			}
			a[low] = a[high];
			while(low < high && a[low] <= temp){
				low ++;
			}
			a[high] = a[low];
		}
		a[low] = temp;
		return low;
	}
	
	private static void swap(int a[], int index, int index2){
		int temp = a[index];
		a[index] = a[index2];
		a[index2] = temp;
	}
	
	public static void print(int a[]){
		for(int i : a){
			System.out.print(i+",");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int a[] = {11, 31, 12, 5, 34, 30, 26, 38, 36, 18};
		QuickSort.sort(a, 0, a.length - 1);
		QuickSort.sort1(a, 0, a.length - 1);
		QuickSort.sort2(a, 0, a.length - 1);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值