pranay_teja
10/8/2018 - 7:31 AM

Heap_Sort

#include<bits/stdc++.h>
using namespace std;

// #Theory #Sorting

void heapSort(vector<int> &a);
void buildHeap(vector<int> &a, int r);
void heapify(vector<int> &a, int ni,int r);
bool valid(int r,int i);
void swap(int &a,int &b);

int main(){
	//freopen("ip.txt","r",stdin);
	int t;
	cin>>t;
	while(t--){
		int n;
		cin>>n;
		vector<int> a(n);
		for(int i=0;i<n;i++){
			cin>>a[i];
		}
		for(int i=0;i<n;i++){
			cout<<a[i]<<" ";
		}
		cout<<endl;
		heapSort(a);
		for(int i=0;i<n;i++){
			cout<<a[i]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

void heapSort(vector<int> &a){
	int n=a.size();
	for(int i=n-1;i>0;i--){
		buildHeap(a,i); // build max heap
		swap(a[i],a[0]);  // swap top element with last element
	}
}
void buildHeap(vector<int> &a, int r){	// r=index of last element
    if(r==0){
        return; // 0 size array
    }
    for(int i=r;i>=0;i--){
        heapify(a,i,r);
    }
    /*
	int k;	// left=2k+1, right=2k+2, k is parent node
	if(r%2==0){
		k=(r-2)/2;  // if last node is even
	}else{
		k=(r-1)/2;
	}
	for(int i=k;i>=0;i--){  // k-> all nodes with atleast 1 child
		heapify(a,k);
	}
	*/
}
void heapify(vector<int> &a, int ni,int r){	// ni=node index
	int left=(2*ni)+1;
	int right=(2*ni)+2;
	int n=a.size();

	if(valid(r,left)==false && valid(r,right)==false){  // if node has no children return
		return;
	}
	if(valid(r,left)==false){	// no left node
		if(a[ni]<a[right]){
			swap(a[ni],a[right]);
		}
		return;
	}
	if(valid(r,right)==false){	// no right node
		if(a[ni]<a[left]){
			swap(a[ni],a[left]);
		}
		return;
	}
	// both nodes exist
	if(a[ni]<a[left]){
		swap(a[ni],a[left]);
	}
	if(a[ni]<a[right]){
		swap(a[ni],a[right]);
	}
}
bool valid(int r,int i){
	if(i>r){	// all indices to the right of r are already sorted and deleted from heap
		return false;
	}
	return true;
}
void swap(int &a, int &b){
	int t=a;
	a=b;
	b=t;
}