前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【排序】快速排序

【排序】快速排序

作者头像
爱笑的架构师
发布2020-09-24 14:50:16
6620
发布2020-09-24 14:50:16
举报
文章被收录于专栏:爱笑的架构师
代码语言:javascript
复制
        /**
	 * 快速排序
	 * @param a
	 * @param low
	 * @param high
	 */
	public static void quickSort(int[] a, int low, int high) {
		int l = low;
		int h = high;
		if (l >= h) {
			return;
		}
		int temp = a[l];
		// 此循环完成了一趟排序,将数组中小于temp的数放在左边,大于temp的元素放在右边
		while (l < h) {
			while (h > l && a[h] > temp) { // 从右往左扫描找到第一个小于temp的元素
				h--;
			}
			if(l<h){
				a[l] = a[h];  // 放在temp左边
				l++;  // i指针右移一位
			}
			
			while (l<h&& a[l] < temp) { // 从左往右扫描找到第一个大于temp的元素
				l++;
			}
			if(l<h){
				a[h] = a[l]; // 放在temp右边
				h--;  // h左移一位
			}
		}// end 一趟排序
		a[l] = temp;  // 将temp放在最终位置
		quickSort(a, low, l-1);   // 递归对temp左边元素进行排序
		quickSort(a, l+1, high);  // 递归对temp右边的元素进行排序
	}

	public static void main(String[] args) {
		int[] a = { 5, 4, 3, 2, 1 };
		quickSort(a, 0, a.length-1);
		for (int num : a) {
			System.out.print(num + " ");
		}
	}

时间复杂度:最好O(nlogn) 最差O(n*n) 平均O(nlogn)

空间复杂度:O(nlogn) 因为需要栈空间辅助

是否稳定:不稳定

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016/08/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档