跳到正文

个人记录

排序算法

Chorsty约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月5日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前

快排

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];
void qsort(int l ,int r)
{
  int i ,j ,mid ,p;
  i = l ,j = r;
  mid = a[l+r>>1];
  do
  {
    while (a[i]<mid) i++;
    while (a[j]>mid) j--;
    if (i <= j)
      swap(a[i++] ,a[j--]);
  }
  while (i<=j);
  if (l<j) qsort(l ,j);
  if (i<r) qsort(i ,r);
}
int main()
{
  int n ,i=1;
  cin >> n;
  for (i=1; i<=n; i++) cin >> a[i];
  qsort(1 ,n);
  for (i=1; i<=n; i++) cout << a[i] <<" ";
  cout << endl;
  return 0;
}

归并(逆序对)

C++
#include <bits/stdc++.h>
#define IAKIOI ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define int long long
using namespace std;
const int N = 5e5 + 10;
int n;
int a[N] ,ans = 0 ,r[N];
void msort(int s ,int t) {
	if (s == t) return;
	int mid = (s+t)/2;
	msort(s ,mid);
	msort(mid+1 ,t);
	int i = s ,j = mid+1 ,p = s;
	while (i <= mid && j <= t) {
		if (a[i] <= a[j]) r[p++] = a[i++];
		else r[p++] = a[j++] ,ans += mid-i+1;
	}
	while (i <= mid) r[p++] = a[i++];
	while (j <= t) r[p++] = a[j++];
	for (int i=s;i<=t;i++) a[i] = r[i];
}
signed main() {
    IAKIOI;
    cin >> n;
    for (int i=1;i<=n;i++) cin >> a[i];
	msort(1 ,n); 
    //for (int i=1;i<=n;i++) cout << a[i] << " ";
    cout << ans;
    return 0;
}
原文