算法学习(1)——快速排序


代码、课程参考:

数据结构——浙江大学

10.1.1 算法概述;10.1.2 选主元;10.1.3 子集划分;10.1.4 算法实现;

算法可视化:

https://www.cs.usfca.edu/~galles/visualization/Algorithms.html

史上最容易理解的《十大经典算法(动态图展示)》


浙江大学陈越姥姥开的这门数据结构讲解非常细致,强烈推荐!1.5倍速播放学习效率极高!

网上有的代码看了下都比较长,陈越姥姥给的算法思路较清晰,代码量少,遂记录之。

算法简介

快速排序的思想是首先选取一个主元,然后将待排序的数组分成大于主元和小于主元的部分,继续对这两部分递归进行快速排序,直至排序完成。

在陈越老师的课程里,主元的选取通过Median3函数实现。这个函数的功能是对待排序数组最左边,中间,最右边的数先进行排序,然后返回中间的数。

快速排序的主要内容还是建议观看视频,这里不再赘述。

C++实现

#include <stdio.h>
#include<iostream>
using namespace std;
int Median3(int A[], int Left, int Right) {
	int Center = (Right + Left) / 2;
	if (A[Left] > A[Center])
		swap(A[Left], A[Center]);
	if (A[Left] > A[Right])
		swap(A[Left], A[Right]);
	if (A[Center] > A[Right])
		swap(A[Center], A[Right]);
	/*A[Left] <= A[Center] <= A[Right]*/
	swap(A[Center], A[Right - 1]);//将主元Pivot藏到右边
	return A[Right - 1];
}

void Quicksort(int A[], int Left, int Right) {
	if (Left >= Right) return;
	int Pivot = Median3(A, Left, Right);
	int i = Left, j = Right-1;
	while(i<j){
		while (A[++i]<Pivot){}
		while (A[--j]>Pivot){}
		if (i < j)
			swap(A[i], A[j]);
	}
	swap(A[i], A[Right - 1]);
	Quicksort(A, Left, i - 1);
	Quicksort(A, i+1,Right);
}

int main() {
	int n;
	cout << "input the size of array" << endl;
	cin >> n;
	int *a = new int[n];
	cout << "input the array" << endl;
	for (int i = 0;i<n;i++) cin >> a[i];
	Quicksort(a, 0, n - 1);
	for (int i = 0;i<n;i++) {
		if (i == 0) cout << a[i];
		else cout << ' ' << a[i];
	}
	cout << endl;
	delete[]a;
	system("pause");
	return 0;
}

 

 

不使用Median3函数选取主元:

#include <stdio.h>
#include<iostream>
using namespace std;

void Quicksort(int a[],int left,int right) {
	if (left >= right) return;
	int Pivot = a[right];
	int i = left-1, j = right;
	while (i < j) {
		while (a[++i] < Pivot);
		while (a[--j] > Pivot);
		if(i<j)
			swap(a[i], a[j]);
	}
	swap(a[i], a[right]);
	Quicksort(a, left, i - 1);
	Quicksort(a, i + 1, right);
}

int main() {
	int n;
	cin >> n;
	int *a = new int[n];
	for (int i = 0;i < n;i++) cin >> a[i];
	Quicksort(a, 0, n - 1);
	for (int i = 0;i < n;i++) {
		if (i == 0) cout << a[i];
		else cout << ' ' << a[i];
	}
	cout << endl;
	delete[]a;
	system("pause");
	return 0;
}

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值