JAVA周报

#include<iostream>
using namespace std;
template<class T>
int length(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}//数组长度
void desc(double *x,double *y){
double temp=0;
if(*x<*y){
temp=*x;
*x=*y;
*y=temp;
}
}//降序
void asc(double *x,double *y){
double temp=0;
if(*x>*y){
temp=*x;
*x=*y;
*y=temp;
}
}//升序
void z(double *t,int nleaf,int n,int num){
int temp;
if(nleaf<=n/2-1){
if(2*nleaf+1<=n-1&&t[2*nleaf+1]>t[nleaf]||2*nleaf+2<=n-1&&t[2*nleaf+2]>t[nleaf]){
if(2*nleaf+1<=n-1&&2*nleaf+2<=n-1){
if(t[2*nleaf+1]>=t[2*nleaf+2]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+1];
t[2*nleaf+1]=temp;
}else{
temp=t[nleaf];
t[nleaf]=t[2*nleaf+2];
t[2*nleaf+2]=temp;
}
}
else{
if(2*nleaf+1<=n-1&&t[2*nleaf+1]>=t[nleaf]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+1];
t[2*nleaf+1]=temp;
}
if(2*nleaf+2<=n-1&&t[2*nleaf+2]>t[nleaf]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+2];
t[2*nleaf+2]=temp;
}
}
}
for(int k=0;k<num;k++){
cout<<t[k]<<" ";
}
cout<<endl;
z(t,2*nleaf+1,n,num);
z(t,2*nleaf+2,n,num);
}
else{
return;
}
}//大顶堆
void z2(double *t,int nleaf,int n,int num){
int temp;
if(nleaf<=n/2-1){
if(2*nleaf+1<=n-1&&t[2*nleaf+1]<t[nleaf]||2*nleaf+2<=n-1&&t[2*nleaf+2]<t[nleaf]){
if(2*nleaf+1<=n-1&&2*nleaf+2<=n-1){
if(t[2*nleaf+1]<=t[2*nleaf+2]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+1];
t[2*nleaf+1]=temp;
}else{
temp=t[nleaf];
t[nleaf]=t[2*nleaf+2];
t[2*nleaf+2]=temp;
}
}
else{
if(2*nleaf+1<=n-1&&t[2*nleaf+1]<=t[nleaf]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+1];
t[2*nleaf+1]=temp;
}
if(2*nleaf+2<=n-1&&t[2*nleaf+2]<t[nleaf]){
temp=t[nleaf];
t[nleaf]=t[2*nleaf+2];
t[2*nleaf+2]=temp;
}
}
}
for(int k=0;k<num;k++){
cout<<t[k]<<" ";
}
cout<<endl;
z2(t,2*nleaf+1,n,num);
z2(t,2*nleaf+2,n,num);
}
else{
return;
}
}//小顶堆
void f(double *t,int n,int num) {
for(int i=n/2-1;i>=0;i--){
int nleaf=i;
z(t,nleaf,n,num);
}
}//大顶堆
void f2(double *t,int n,int num) {
for(int i=n/2-1;i>=0;i--){
int nleaf=i;
z2(t,nleaf,n,num);
}
}//小顶堆
void g(double *t,int n){
int temp;
cout<<"初次构建:"<<endl;
f(t,n,n);
for(int i=n-1;i>=1;i--){
temp=t[0];
t[0]=t[i];
t[i]=temp;
cout<<"调整:"<<endl;
f(t,i,n);
}
cout<<"结果:";
for(int k=0;k<n;k++){
cout<<t[k]<<" ";
}
cout<<endl;

} //大
void g2(double *t,int n){
int temp;
cout<<"初次构建:"<<endl;
f2(t,n,n);
for(int i=n-1;i>=1;i--){
temp=t[0];
t[0]=t[i];
t[i]=temp;
cout<<"调整:"<<endl;
f2(t,i,n);
}
cout<<"结果:";
for(int k=0;k<n;k++){
cout<<t[k]<<" ";
}
cout<<endl;

} //小
int main(){
cout<<"请输入排序个数:"<<endl;
int n;
cin>>n;
double* action=new double[n];
cout<<"请输入排序序列:"<<endl;
for(int i=0;i<n;i++){
cin>>action[i];
}
cout<<"请选择排序方向:"<<endl;
cout<<"a.从小到大"<<endl;
cout<<"b.从大到小"<<endl;
char act;
cin>>act;
if(act=='a'){
g(action,n);
}else if(act=='b'){
g2(action,n);
}else{
cout<<"请按要求输入!!!"<<endl;
}

}

posted @ 2021-07-18 19:21  我的未来姓栗山  阅读(35)  评论(0编辑  收藏  举报