2017-12-13 24 views
0

숫자 1,2,4,3,5,6,으로 구성된 배열이 있다고 가정하십시오. heaport를 사용하여 1,3,5,7,2,4,6를 인쇄하려고합니다. 기본 힙을 수정하려고했지만 올바른 결과를 얻지 못했습니다.먼저 짝수 번호의 순서를 인쇄하고 힙을 사용하는 작은 번호 대신에 어떻게 인쇄 할 수 있습니까?

도와 주시겠습니까?

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

int heapsize; 

int make_left(int i) 
{ 
    return 2*i; 
} 
int make_right(int i) 
{ 
    return (2*i)+1; 
} 
void max_heapify(int a[],int i) 
{ 
    // cout<<heapsize<<endl; 
    int largest=i; 
    // printf("current position of largest is %d and largest is %d\n",largest,a[largest]); 


    int l=make_left(i); 
    int r=make_right(i); 
// printf("current position of left is %d and left element is %d\n",l,a[l]); 
    // printf("current position of right is %d and right element is %d\n",r,a[r]); 

    if(a[l]>=a[largest] && l<=heapsize && a[l]%2!=0) 
     largest=l; 
    if(a[r]>a[largest] && r<=heapsize && a[l]%2!=0) 
     largest=r; 
    //printf("Finalcurrent position of largest is %d and largest is %d\n",largest,a[largest]); 

    if(largest!=i) 
    { 
     swap(a[i],a[largest]); 
     max_heapify(a,largest); 
    } 
} 
void buildmax(int a[],int n) 
{ 
for (int i=n/2;i>=1;i--) 
    { 
    // printf("main theke call\n"); 
     max_heapify(a,i); 
    } 
} 
void heapsort(int a[],int n) 
{ 
    buildmax(a,n); 
// printf("After being buildmax\n"); 
    // for (int i=1;i<=n;i++) 
    //{ 
     //printf("i is %d\n",i); 
     // cout<<a[i]<<endl; 

    //} 
    for (int i=n;i>=2;i--) 
    { 
     // printf("1st element is %d and last elemenet is %d\n",a[1],a[heapsize]); 

     swap(a[1],a[heapsize]); 
     //printf("1st element is %d and last elemenet is %d\n",a[1],a[heapsize]); 
     heapsize--; 
     max_heapify(a,1); 
    } 

} 


int main() 
{ 

    int n; 
    cin>>n; 
    heapsize=n; 

    int a[n]; 
    printf("The elements are\n"); 
    for (int i=1;i<=n;i++) 
    { 
     cin>>a[i]; 
    } 
    heapsort(a,n); 

    printf("After being sorted\n"); 
    for (int i=1;i<=n;i++) 
    { 
     //printf("i is %d\n",i); 
     cout<<a[i]<<endl; 
    } 
} 
+0

이란 무엇입니까 구체적인 문제? 코드 게시! – MrSmith42

+0

나는 그 아이디어만을 찾고 있었다. 그러나 편집하고 코드를 게시했습니다 –

+1

홀수가 항상 앞에 오도록 비교 규칙을 변경하십시오. 하위 비트에 사전 식 정렬을 사용한 다음 값을 지정하십시오. –

답변

4

당신은 새로운 기능을 모든 곳에서 이전과 단지 (당신이 비교 것을 사용하는 것보다 이상) 운영자 미만 교체 같은 힙 정렬 알고리즘을 사용할 수 있습니다

bool LessThan(int a, int b) 
{ 
    if (a%2 == 1 && b%2 == 0) 
    return true; 
    if (a%2 == 0 && b%2 == 1) 
    return false; 
    return a < b; 
}