排序专题

快速排序

void quicksort(int a[], int s, int t) { //快速排序
	if (s < t) {
		int low = s, high = t;
		int p = a[low];
		while (low < high) {
			while (low <= high && a[high] >= p) high--;
			a[low] = a[high];
			while (low <= high && a[low] <= p) low++;
			a[high] = a[low];
		}
		a[low] = p;
		for (int i = 1; i <= n; i++) {
			cout << a[i] << " \n"[i == n];
		}
		quicksort(a, s, low - 1);
		quicksort(a, low + 1, t);
	}
}
void qsort(int s,int t){//快速排序优化版 
	if(s<t){
		int i=s,j=t;
		int p=a[(i+j)/2];
		while(i<=j){
			while(a[i]<p) i++;
			while(a[j]>p) j--;
			if(i<=j){
				swap(a[i],a[j]);
				i++,j--;
			}
		}
		if(j>s) qsort(s,j);
		if(i<t) qsort(i,t);
	}
}

归并排序

void mergersort(int s, int t) {
	if (s < t) {
		int mid = (s + t) / 2;
		mergersort(s, mid);
		mergersort(mid + 1, t);
		int l = s, r = mid + 1, k = s;
		while (l <= mid && r <= t) {
			if (a[l] <= a[r]) c[k++] = a[l++];
			else {
				c[k++] = a[r++];
				cnt += (mid - l + 1);
			}
		}
		while (l <= mid) c[k++] = a[l++];
		while (r <= t) c[k++] = a[r++];
		for (int i = s; i <= t; i++) a[i] = c[i];
	}
}

直接插入排序

void insert(int a[], int n) { //直接插入排序
	for (int i = 2; i <= n; i++) {
		if (a[i] < a[i - 1]) {
			a[0] = a[i];
			int j;
			for (j = i - 1; a[j] > a[0]; j--) {
				a[j + 1] = a[j];
			}
			a[j + 1] = a[0];
		}
	}
}

堆排序

for (int i = n / 2; i >= 1; i--) down(i);
for (int i = 1; i < n; i++) {
	swap(a[1], a[r]);
	r--;
	down(1);
}
void down(int u) {
	int t = u;
	if (2 * u <= r && a[2 * u] > a[t]) t = 2 * u;
	if (2 * u + 1 <= r && a[2 * u + 1] > a[t]) t = 2 * u + 1;
	if (t != u) {
		swap(a[t], a[u]);
		down(t);
	}
}

基数排序

	int sum = 0;
	while (mx) {
		mx /= 10;
		sum++;
	}
	int cnt = 1;
	for (int k = 1; k <= sum; k++) {
		for (int i = 0; i < n; i++)
			v[a[i] / cnt % 10].push_back(a[i]);
		a.clear();
		for (int i = 0; i <= 9; i++) {
			for (auto t : v[i])
				a.push_back(t);
			v[i].clear();
		}
		cnt *= 10;
		for (auto t : a)
			cout << t << ' ';
		cout << '\n';
	}

希尔排序

void shellsort(int a[],int dk){//希尔排序 
	for(int i=1+dk;i<=n;i++){
		if(a[i]<a[i-dk]){
			a[0]=a[i];
			for(int j=i-dk;a[j]>a[0];j-=dk){
				a[j+dk]=a[j];
			}
			a[j+dk]=a[0];
		}
	}
}
posted @ 2024-07-05 17:49  ZhangDT  阅读(0)  评论(0编辑  收藏  举报