Day 45 算法笔记之提高篇(3)9.7 堆

目录

1.堆的定义

2.向下调整

3.建堆

4.删除堆顶

5.向上调整

6.插入元素

7.堆排序

8.Insertion or Heap Sort


1.堆的定义

const int maxn=100;

int heap[maxn],n=10;

2.向下调整

void downadjust(int low,int high){
	int i = low,j=i*2;
	while(j<=high){
		if(j+1<=high&&heap[j+1]>heap[j]){
			j = j+1;
		}
		if(heap[j]>heap[i]){
			swap(heap[j],heap[i]);
			i = j;
			j = i*2;
		}else{
			break;
		}
	}
}

3.建堆

void createheap(){
	for(int i=n/2;i>=1;i--){
		downadjust(i,n);
	}
}

4.删除堆顶

void deletetop(){
	heap[1] = heap[n--];
	downadjust(1,n);
}

5.向上调整

void upadjust(int low,int high){
	int i=high,j=i/2;
	while(j>=low){
		if(heap[j]<heap[i]){
			swap(heap[j],heap[i]);
			i = j;
			j = i/2;
		}
	}else{
		break;
	}
}

6.插入元素

void insert(int x){
	heap[++n] = x;
	upadjust(1,n);
}

7.堆排序

void heapsort(){
	createheap();
	for(int i=n;i>1;i--){
		swap(heap[i],heap[1]);
		downadjust(1,i-1);
	}
}

8.Insertion or Heap Sort

#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

const int N = 111;
int orign[N],tempori[N],changed[N];

int n;
bool issame(int a[],int b[]){
	for(int i=1;i<=n;i++){
		if(a[i]!=b[i]) return false;
	}
	return true;
}

bool showarray(int a[]){
	for(int i=1;i<=n;i++){
		printf("%d",a[i]);
		if(i<n) printf(" ");
	}
	printf("\n");
}

bool insertsort(){
	bool flag = false;
	for(int i=2;i<=n;i++){
		if(i!=2&&issame(tempori,changed)){
			flag = true;
		}
		sort(tempori,tempori+i+1);
		if(flag==true){
			return true;
		}
	}
	return false;
}

void downadjust(int low,int high){
	int i=low,j=i*2;
	while(j<=high){
		if(j+1<=high&&tempori[j+1]>tempori[j]){
			j+=1;
		}
		if(tempori[j]>tempori[i]){
			swap(tempori[j],tempori[i]);
			i = j;
			j = i*2;
		}else{
			break;
		}
	}
}

void heapsort(){
	bool flag=false;
	for(int i=n/2;i>=1;i--){
		downadjust(i,n);
	}
	for(int i=n;i>1;i--){
		if(i!=n&&issame(tempori,changed)){
			flag=true;
		}
		swap(tempori[i],tempori[1]);
		downadjust(1,i-1);
		if(flag==true){
			showarray(tempori);
			return;
		}
	}
}

int main(){
	
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&orign[i]);
		tempori[i] = orign[i];
	}
	
	for(int i=1;i<=n;i++){
		scanf("%d",&changed[i]);
	}
	
	if(insertsort()){
		printf("Insertion Sort\n");
		showarray(tempori);
	}else{
		printf("Heap Sort\n");
		for(int i=1;i<=n;i++){
			tempori[i] = orign[i];
		}
		heapsort();
	}
	
	return 0;
}

おすすめ

転載: blog.csdn.net/aixiaoxiao13/article/details/121480437