各种排序模板

1.冒泡排序

void Bubble_Sort(int arr[]) {
	for(int i = n; i >= 2; i--) {
		for(int j = 1; j <= i - 1; j++) {
			if(arr[j] >= arr[j + 1]) swap(arr[j], arr[j + 1]);
		}
	}
}

拓展:求逆序对

int Bubble_Sort(int arr[]) {
	int sum = 0;
	for(int i = n; i >= 2; i--) {
		for(int j = 1; j <= i - 1; j++) {
			if(arr[j] >= arr[j + 1]) swap(arr[j], arr[j + 1]), sum++;
		}
	}
	return sum;
}

2.选择排序

void Selection_Sort(int arr[]) {
	for(int i = 1; i <= n - 1; i++) {
		for(int j = i + 1; j <= n; j++) {
			if(arr[i] >= arr[j]) swap(arr[i], arr[j]);
		}
	}
}

3.桶排

#include <iostream>
using namespace std;

const int MAXN = 1005;
const int MAXARR = 100005;
const int INF = 0x3f3f3f3f;
int n, a[MAXN], bak[MAXARR];

int Max(int x, int y) {return x > y ? x : y;}

void Bucket_Sort(int arr[]) {
	int _max = -INF;
	for(int i = 1; i <= n; i++) bak[arr[i]]++, _max = Max(arr[i], _max);
	
	for(int i = 1; i <= _max; i++) {
		while(bak[i] > 0) {
			cout << i << " ";
			bak[i]--;
		}
	}
	return;
}

int main() {
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> a[i];
	Bucket_Sort(a);
	return 0;
}

4.快速排序

void Quick_Sort(int l, int r) {
	if(l > r) return;
	int i = l, j = r, mid = arr[l];
	while(i != j) {
		while(arr[j] >= mid && i != j) j--;
		while(arr[i] <= mid && i != j) i++;
		if(i != j) swap(arr[i], arr[j]);
	}
	swap(arr[l], arr[i]);
	Quick_Sort(l, i - 1);
	Quick_Sort(i + 1, r);
}

5.归并排序

void Merge_Sort(int l, int r) {
	if(l == r) return;
	int mid = (l + r) / 2;
	Merge_Sort(l, mid);
	Merge_Sort(mid + 1, r);
	
	int i = l, j = mid + 1;
	int ans[MAXN], len = l;
	while(i <= mid && j <= r) {
		if(arr[i] < arr[j]) ans[len++] = arr[i++];
		else ans[len++] = arr[j++];
	}
	while(i <= mid) ans[len++] = arr[i++];
	while(j <= r) ans[len++] = arr[j++];
	for(int i = l; i <= r; i++) arr[i] = ans[i];
	return;
}

拓展:逆序对(写本文的终极目的)

火柴排队

题解

6.堆排序

#include <iostream>
using namespace std;

const int MAXN = 1005;
int n, len;
int a[MAXN], heap[MAXN];

void put(int);
void pop();
int get();

int main() {
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> a[i], put(a[i]);
	for(int i = 1; i <= n; i++) cout << get() << " ", pop();
	return 0;
}

void put(int x) {
	heap[++len] = x;
	int fa, now = len;
	while(now > 1) {
		fa = now >> 1;
		if(heap[fa] <= heap[now]) break;
		swap(heap[fa], heap[now]);
		now = fa;
	}
	return;
}

int get() {
	return heap[1];
}

void pop() {
	heap[1] = heap[len--];
	int son, now = 1;
	while((now << 1) <= len) {
		son = now << 1;
		if(heap[son + 1] <= heap[son]) son = son + 1;
		if(heap[now] <= heap[son]) break;
		swap(heap[now], heap[son]);
		now = son;
	}
	return;
}
posted @ 2020-07-25 21:18  C2022lihan  阅读(48)  评论(0编辑  收藏  举报