自研排序——栈排序
  • 板块学术版
  • 楼主xingjielongSYH
  • 当前回复9
  • 已保存回复9
  • 发布时间2024/8/31 10:34
  • 上次更新2024/8/31 13:56:22
查看原帖
自研排序——栈排序
1436254
xingjielongSYH楼主2024/8/31 10:34
/*
1.建立三个栈a,b,c
2.读取原数组,顺序置入c
重复:
	重复直到c为空:
		3.取出c.top元素
		4.若b为空,把该元素置入b
		  否则与b.top比较,若大于等于b.top,则放入b栈,反之放入a栈
	5.若a为空,则由将b下至上存入答案数组(手写栈),退出循环
   否则: 
		6.由上至下把b的元素移至c上
		7.由上至下把a的元素移至c上
*/
#include<bits/stdc++.h>
using namespace std;
void stack_sort(int a[],int l,int r){
	int sa[r],sb[r-l],sc[r-l];
	int la=0,lb=0,lc=0;
	for(int i=l;i<=r;i++)sc[++lc]=a[i];
	while(1){
		while(lc){
			int top=sc[lc--];
			if(!lb)sb[++lb]=top;
			else{
				if(top>=sb[lb])sb[++lb]=top;
				else sa[++la]=top;
			}
		}
		if(!la){
			for(int i=1;i<=lb;i++)a[i+l-1]=sb[i];
			break;
		}
		while(lb)sc[++lc]=sb[lb--];
		while(la)sc[++lc]=sa[la--];
	}
	
}
int main(){
	int n,a[1000];
	cin >>n;
	for(int i=1;i<=n;i++)cin >> a[i];
	stack_sort(a,1,n);
	for(int i=1;i<=n;i++)cout << a[i] << " ";
}
//时间复杂度:O(n^2) 不确定
//空间复杂度:O(n)
//不稳定
//有没有大佬能解释一下原理()
//或者给出时间复杂度()
2024/8/31 10:34
加载中...