C/C++/MFC
C기초 힙 정렬(HEAP SORT)
2008.03.14 23:51
힙 정렬(HEAP SORT)
<결과>
Sorted elements are : 1 2 3 4 7 9 22 33 44 55 77 88
// win4.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. //
#include "stdafx.h" #include<iostream> #include<iomanip> using namespace std;
class CWATHeapSort { private: int *x; int items; public: CWATHeapSort(int); ~CWATHeapSort(); void input(int []); void heap_property(int,int); void construct_heap(); void display(); void sort(int []); };
CWATHeapSort::CWATHeapSort(int n) { items=n; x=new int[items+1]; }
CWATHeapSort::~CWATHeapSort() { delete [] x; }
void CWATHeapSort::input(int a[]) { for(int i=0;i<=items;i++) x[i]=a[i-1]; }
void CWATHeapSort::display() { cout<<"\n Sorted elements are :"; for(int i=1;i<=items;i++) cout<<setw(5)<<x[i]; }
void CWATHeapSort::construct_heap() { for(int i=items/2;i>0;i--) heap_property(i,items); }
void CWATHeapSort::heap_property(int root, int limit) { int done=0; int big=x[root]; int j=2*root; while((j<=limit) && (done==0)) {
if((j<limit) && (x[j]<x[j+1])) j++; if(big >=x[j]) done=1; else { x[j/2]=x[j]; j=2*j; } } x[j/2]=big; }
void CWATHeapSort::sort(int a[]) { construct_heap(); for(int i=(items-1);i>0;i--) { int temp; temp=x[i+1]; x[i+1]=x[1]; x[1]=temp; a[i]=x[i+1]; heap_property(1,i); } a[0]=x[1]; }
int main() { int a[100]={1,2,3,4,7,9,44,33,22,55,77,88,}; int n=12;
CWATHeapSort obj(n); obj.input(a); obj.sort(a); obj.display(); return 0; }
<결과>
Sorted elements are : 1 2 3 4 7 9 22 33 44 55 77 88
관련 문서가 검색되었습니다.
- [2013/06/20] 5명의 키를 읽어 들여 가장 큰 키와 작은 키를 구하는 프로그램을 작성하시오 (12064) *1
- [2011/03/29] C# DataGridView 간단하게 필터 기능 사용하기 (27985)
- [2010/09/17] ListView Sort 정렬하기 (22346) *1
- [2008/03/14] 쉘 정렬(SHELL SORT) (12234)
- [2008/03/14] 퀵 정렬(QUICK SORT) (27213)
- [2008/03/14] 버블 정렬(BUBBLE SORT) (13053)
- [2008/03/14] 합병정렬(MERGE SORT) (12275)
댓글 0
번호 | 제목 |
---|---|
공지 | 몇 가지 TIP 모음 |
공지 | Dialog 형태의 프로그램 만들기 [2] |
공지 | Visual C++ 에 유용한 링크 모음입니다. |
» | 힙 정렬(HEAP SORT) |