Ejemplo n.º 1
0
int main(){

printf("\nLets create heap\n");
getch();
Heap* heap=CreateHeap(1);

int n;
printf("\nEnter the number of elements you want to create array with : ");
scanf("%d",&n);
int* Array=(int*)malloc(sizeof(int)*n);
int i;
printf("\nEnter elements of array\n");
for(i=0;i<n;i++){
scanf("%d",&Array[i]);
}
printf("\nEnter the value of k : ");
int k;
scanf("%d",&k);
BuildHeap(heap,Array,k+1);
printf("\nPress enter to get sort elements\n");
getch();
SortAll(heap,Array,n,k);
printf("\nSorted\n\n");
//In place sorting in Array itself

for(i=0;i<n;i++){
printf("%d  ",Array[i]);
}
getch();
return 0;
}
Ejemplo n.º 2
0
////////////////////////////// HeapSort /////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
void
HeapSort( LPSORTDATA       lpData,
          LPENTITYINSTANCE lpEI[],
          zULONG           ulRecordCnt )
{
   BuildHeap( lpData, lpEI, ulRecordCnt );

   zULONG ulHoldCnt = ulRecordCnt;
   zULONG ulHoldMax = ulMaxRecords;
   zULONG *p1;
   zULONG ul;
   while ( ulRecordCnt > 1 )
   {
      ulRecordCnt--;
      m_lMaxRecords--;

      p1 = CSIMP_GETSORTIDX_PTR( ulRecordCnt + 1, m_pUseIdx->m_pxIdx );
      ul = *p1;
      *p1 = *(m_pUseIdx->m_pxIdx);
      *(m_pUseIdx->m_pxIdx) = ul;

      ul = Heapify( 1 );
      while ( ul )
      {
         ul = Heapify( ul );
      }
   }

   ulRecordCnt = ulHoldCnt;
   m_lMaxRecords = ulHoldMax;
}
Ejemplo n.º 3
0
void HeapSort::sort(int* array, int size)
{
	
   m_array= new int[size +1];
   for(int i=0; i<size; i++)
   {
	   m_array[i+1]= array[i];
   }
   BuildHeap(m_array,size);
   for(i=1; i<=10; i++)
   {
	   cout<<m_array[i]<<endl;
   }
   int tmp;
   for(int j=size; j>=1; j--)
   {
	   MaxHeapify(m_array, 1, j);
	   tmp=m_array[1];
	   m_array[1] = m_array[j];
	   m_array[j]=tmp;
   }
   for(int k=1; k<size+1 ; k++)
   {
	   array[k-1]=m_array[k];
   }
   delete[] m_array;

   

};
Ejemplo n.º 4
0
void HeapSort(ElementType *array, int length)
{
	for(int i = length / 2; i >=0; i--)
		BuildHeap(array, i, length);
	for(i = N - 1; i > 0; i--)
	{
		/**
		 * 核心部分:
		 * 删除最大值(根节点)并将其放在最后一位(最后一位放到根节点)
		 * 这样做不用另外开辟空间来接收删除的元素
		 * 然后从根节点开始,从新构造堆序
		 */
		swap(&array[0], &array[i])
		BuildHeap(array, 0, i);
	}
}
Ejemplo n.º 5
0
void CHeapSort::getMax(ModStruct *A, int hLen,int *Node_Rank)
{
	double tempMod;
	int tempNode;
	if(renew==true)
	{
		BuildHeap(A, hLen,Node_Rank);      //建堆 
		tempMod = A[hLen-1].dMod;    //交换堆的第一个元素和堆的最后一个元素
		tempNode = A[hLen-1].node;
		A[hLen-1].dMod = A[0].dMod;
		A[hLen-1].node = A[0].node;
		A[0].dMod = tempMod;
		A[0].node = tempNode;
		//hLen--;        //堆的大小减一
		//AdjustHeap(A, hLen, 0,Node_Rank);  //调堆
		
	}
	else
	{
		/*
		tempMod = A[hLen-1].dMod;    //交换堆的第一个元素和堆的最后一个元素
		tempNode = A[hLen-1].node;
		A[hLen-1].dMod = A[0].dMod;
		A[hLen-1].node = A[0].node;
		A[0].dMod = tempMod;
		A[0].node = tempNode;
		hLen--;        //堆的大小减一
		*/
		AdjustHeap(A, hLen, 0,Node_Rank);  //调堆
	}
}
Ejemplo n.º 6
0
int main(int argc, const char * argv[])
{
    int k;
    int i;
    scanf("%d",&k);
    
    int *heap = (int* )malloc(k+1);
    
    FILE *fp = fopen("data.txt", "r");
    
    for (i = 1; i<=k; i++) {
        fscanf(fp, "%d ",&heap[i]);
    }
    
    BuildHeap(heap, k);
    int data;
    while (fscanf(fp, "%d ",&data) != EOF) {
        if (data < heap[1]) {
            heap[1] = data;
            MaxHeap(heap, 1, k);
        }
    }
    for (i=1; i<=k; i++) {
        printf("%d ",heap[i]);
    }
    printf("\n");
    fclose(fp);
    free(heap);
    
    return 0;
}
Ejemplo n.º 7
0
int* maxSlidingWindow2(int* nums, int numsSize, int k, int* returnSize) {
  if (nums == NULL || numsSize == 0)
    return NULL;
  
  Result R;
  ElementType* Heap;
  ElementType Node;
  Queue Q;
  int i;

  Q = Initialize(MAX);
  R = InitializeResult(MAX);
  Heap = InitHeap(nums, k, Q);
  BuildHeap(Heap, k);

  for (i = k; i < numsSize; ++i)
  {
    AddToResult(R, Heap[1] -> Value);
    Node = Dequeue(Q);
    Node -> Value = nums[i];
    Enqueue(Q, Node);
    AdjustRandItemInHeap(Heap, Node -> Index, k);
  }

  AddToResult(R, Heap[1] -> Value);
  *returnSize = R -> Size;
  return R -> Next;
}
Ejemplo n.º 8
0
/*堆排序,直接调用了之前编写的二叉堆代码*/
void HeapSort(ElementType A[], int N)
{
	int i;
	PriorityQueue H = BuildHeap(A, N);
	for(i=0; i<N; i++)
		A[i] = DeleteMin(H);

	Destroy(H);
}
Ejemplo n.º 9
0
//堆排序
void HeapSort(int *a,int n){

    BuildHeap(a, n);
    for (int i = n - 1; i >= 0; i--) {
        //交换堆顶和最后一个元素,即每次将剩余元素中的最大者放到后面;
        swap(&a[0], &a[i+1]);
        //重新调整堆为大顶堆;
        HeapAdjust(a, 0, i );
    }
}
Ejemplo n.º 10
0
Archivo: 47.c Proyecto: 13436120/Cgames
void Heap_Sort(int n)
{ /* 对R[1..n]进行堆排序,不妨用R[0]做暂存单元 */
    int i;
    BuildHeap(n); /* 将R[1-n]建成初始堆 */
    for(i=n;i>1;i--)
    { /* 对当前无序区R[1..i]进行堆排序,共做n-1趟。 */
    	R[0]=R[1]; R[1]=R[i];R[i]=R[0]; /* 将堆顶和堆中最后一个记录交换 */
    	Heapify(1,i-1); /* 将R[1..i-1]重新调整为堆,仅有R[1]可能违反堆性质 */
    } /* end of for */
} /* end of Heap_Sort */
Ejemplo n.º 11
0
struct Heap* createAndBuildHeap(char data[], int freq[], int size)
{
    int i;
    struct Heap* Heap = BuildHeap(size);
    for (i = 0; i < size; ++i)
        Heap->array[i] = newNode(data[i], freq[i]);
    Heap->size = size;
    buildHeap(Heap);
    return Heap;
}
Ejemplo n.º 12
0
void HeapSort(int *a, int size)    //堆排序 
{
    int i;
    BuildHeap(a, size);
    for(i = size - 1; i > 0; i--)
    {
        swap(a[0], a[i]);           //交换堆顶和最后一个元素,即每次将剩余元素中的最大者放到最后面 
		//BuildHeap(a, i-1);        //将余下元素重新建立为大顶堆 
		HeapAdjust(a, 0, i);  		//重新调整堆顶节点成为大顶堆
    }
} 
Ejemplo n.º 13
0
void LargestKNumber(const std::vector<int> &vec, int k, std::vector<int> &heap) {
    heap.insert(heap.end(), vec.begin(), vec.begin() + k);
    BuildHeap(heap);
    for (int i = k; i < vec.size(); i++) {
        if (vec[i] > heap[0]) {
            heap[0] = heap.back();
            heap.pop_back();
            Heapify(heap, 0);
            InsertHeap(heap, vec[i]);
        }
    }
}
Ejemplo n.º 14
0
void HeapSort(int *heap,int len)
{
	int i;
	int size = len;
	BuildHeap(heap,size);

	for(i=size-1;i>=1;i--)
	{
		swap(heap,0,i);
		size--;
		MaxHeap(heap,0,size);
	}
}
Ejemplo n.º 15
0
void SortingHeap(int *array, int left, int right)
{
    int size = right - left + 1;
    BuildHeap(array, size);
    int i;
    for(i = size - 1; i >= 1; i--)
    {
        int helper = array[0];
        array[0] = array[i];
        array[i] = helper;
        --size;
        RepairHeap(array, 0, size);
    }
}
Ejemplo n.º 16
0
void MaxHeap::Sort(std::vector<int>& v)
{
	int size = (int)v.size();
	if (size > 0)
	{
		BuildHeap(v, size);
		for (int i = size - 1; i > 0; i--)
		{
			int t = v[i];
			v[i] = v[0];
			v[0] = t;
			size -= 1;
			Heapify(v, size, 0);
		}
	}
}
Ejemplo n.º 17
0
void HeapSort(int num[] ,int size)
{
    int i;
    int iLength=size;
     
    PrintHeap("Befor Sort:",num,iLength);
     
    BuildHeap(num,size);// 建立小顶堆  
     
    for (i = iLength - 1; i >= 1; i--) {  
        Swap(num, 0, i);// 交换  
        size--;// 每交换一次让规模减少一次  
        PercolateDown(num, 0,size);// 将新的首元素下滤操作
        PrintHeap("Sort Heap:",num,iLength); 
    }
}
Ejemplo n.º 18
0
//----------------------------------------------------------------------------
VertexCollapse::VertexCollapse (int iVQuantity, Vector3*& rakVertex,
    bool bClosed, int*& raiMap, int& riEQuantity, int*& raiEdge)
{
    raiMap = new int[iVQuantity];

    if ( bClosed )
    {
        riEQuantity = iVQuantity;
        raiEdge = new int[2*riEQuantity];

        if ( iVQuantity == 3 )
        {
            raiMap[0] = 0;
            raiMap[1] = 1;
            raiMap[2] = 3;
            raiEdge[0] = 0;  raiEdge[1] = 1;
            raiEdge[2] = 1;  raiEdge[3] = 2;
            raiEdge[4] = 2;  raiEdge[5] = 0;
            return;
        }
    }
    else
    {
        riEQuantity = iVQuantity-1;
        raiEdge = new int[2*riEQuantity];

        if ( iVQuantity == 2 )
        {
            raiMap[0] = 0;
            raiMap[1] = 1;
            raiEdge[0] = 0;  raiEdge[1] = 1;
            return;
        }
    }

    // create the heap of records
    InitializeHeap(iVQuantity,rakVertex,bClosed);
    BuildHeap();
    assert( IsValid() );

    // create the level of detail information for the polyline
    int* aiCollapse = new int[iVQuantity];
    CollapseVertices(iVQuantity,rakVertex,aiCollapse);
    ComputeEdges(iVQuantity,bClosed,aiCollapse,raiMap,riEQuantity,raiEdge);
    ReorderVertices(iVQuantity,rakVertex,aiCollapse,riEQuantity,raiEdge);
    delete[] aiCollapse;
}
Ejemplo n.º 19
0
	NOINLINE int SearchContext::Search(float searchLx, float searchLy, float searchHx, float searchHy, const int32_t count, Point* out_points)
	{
		this->searchWindow[0] = searchLx;
		this->searchWindow[1] = searchLy;
		this->searchWindow[2] = -searchHx;
		this->searchWindow[3] = -searchHy;

		HeapItem * heapEnd;
		if (levels > 1)
		{
			ProcessTopGrid(childrenToCheck[0]);
			for (unsigned i = 1; i < levels - 1; ++i)
			{
				ProcessIntermediateGrid(childrenToCheck[i - 1], childrenToCheck[i]);
			}
			heapEnd = ProcessLowestGrid(childrenToCheck[levels - 2], heap);
		}
		else
		{
			static const unsigned top[] = { 0, 1, -1 };
			heapEnd = ProcessLowestGrid(top, heap);
		}

		FixHeap(heap, heapEnd);
		BuildHeap(heap, heapEnd);

		int found = 0;

		while (heap != heapEnd)
		{
			const Point * pt = PopHeapRoot(heap, heapEnd);

			*out_points++ = *pt;
			if (++found == count)
			{
				break;
			}
		}

		return found;
	}
Ejemplo n.º 20
0
int main ()
{
	int heapSize = 12;
	int intArray[4] = {4, 6, 2, 8};
	heapHndl testHeap, builtHeap;

	testHeap = NewHeap (heapSize);

	if (IsEmpty (testHeap))
	{
		printf ("working\n");
	}

	Insert (testHeap, 9);
	Insert (testHeap, 3);
	Insert (testHeap, 5);
	Insert (testHeap, 2);
	Insert (testHeap, 32);
	Insert (testHeap, 6);
	Insert (testHeap, 1);
	Insert (testHeap, 43);
	Insert (testHeap, 23);
	Insert (testHeap, 42);
	Insert (testHeap, 65);
	Insert (testHeap, 57);
	if (IsFull (testHeap))
	{
		printf ("heap currently full\n");
	}
	DeleteMax (testHeap);

	builtHeap = BuildHeap (5, intArray, 4);

	printf ("%d\n", MaxValue (testHeap));
	printf ("%d\n", MaxValue (builtHeap));

	FreeHeap (testHeap);
	FreeHeap (builtHeap);

	return 0;
}
Ejemplo n.º 21
0
	void Balance(bool complete) {
		if (!complete) {
			// photon-map was not filled to capacity;
			// this means we must now get rid of the
			// excess reserved NULL nodes
			size_t nullNodeIdx = 1;

			// find the first node that is still NULL
			while (nullNodeIdx < nodes.size() && nodes[nullNodeIdx] != NULL) {
				nullNodeIdx++;
			}

			// shrink the vector
			if (nullNodeIdx < nodes.size()) {
				nodes.resize(nullNodeIdx);
			}
		}

		if (nodes.size() > 1) {
			// use two temporary buffers for balancing
			//
			// at every level of the recursion, these
			// represent and store the left and right
			// subtrees with respect to the new median
			// point along the splitting axis (subtrees
			// are delineated by start- and end-indices)
			//
			// note: could we do this in-place instead?
			std::vector<T> lftSegment(nodes.size(), NULL);
			std::vector<T> rgtSegment(nodes.size(), NULL);

			for (size_t i = 0; i < nodes.size(); i++) {
				lftSegment[i] = NULL;
				rgtSegment[i] = nodes[i];
			}

			BalanceSegment(lftSegment, rgtSegment, 1, 1, (nodes.size() - 1));
			BuildHeap(lftSegment);
		}
	}
//从M个降序数组中找最大的N个数
//利用堆O(NlogM)
void getMax(int a[][N], int *max)
{
    ElemType *heap = new ElemType[M];//所需的大根堆
    memset(heap, 0, sizeof(ElemType)*M);
    int arrayiter[M];//记录每个数组当前要取的元素
    for (int i = 0; i < M; ++i)
    {
        heap[i].value = a[i][0];
        heap[i].array = i;
        arrayiter[i] = 1;
    }
    BuildHeap(heap, M);
    for (int i = 0; i < N; i++)
    {
        max[i] = heap[0].value;//将堆顶存入数组
        int iter = (arrayiter[heap[0].array]);
        heap[0].value = a[heap[0].array][iter];//将数组下一个放入堆顶
        arrayiter[heap[0].array]++;//对应的数组指针加1
        AdjustDown(heap, 0, M);//调整为大根堆
    }
    delete heap;
}
Ejemplo n.º 23
0
Archivo: e11.cpp Proyecto: cqiyi/kaoshi
void Heapsort() {
	/*对R[1...n]进行堆排序,用R[0]做暂存单元*/
	int i,k;
	BuildHeap();
	for (i=n; i>1; i--) {
		R[0]=R[1];
		R[1]=R[i];
		R[i]=R[0];
		if (i==(n-m+1)) {
			printf("第%d趟的结果是:",m);
			for (k=1; k<=n; k++)
				printf("%5d",R[k].key);
			printf("\n");
			printf("请输入还要输出第几趟结果,不想输出时请输入0:");
			scanf("\n%d",&m);
		}
		Heapify(1,i-1);
	}
	printf("最终排序结果是:");
	for (k=1; k<=n; k++)
		printf("%5d",R[k].key);
	printf("\n");
}/*Heapsort*/
Ejemplo n.º 24
0
void Kruskal(Graph G)
{
	int EdgesAccepted;
	DisjSet S;
	PriorityQueue H;
	Vertex U, V;
	SetType Uset, Vset;
	Edge E;

	Initialize(S);
	ReadGraphIntoHeapArray(G, H);
	BuildHeap(H);

	EdgesAccepted = 0;
	while (EdgesAccepted < NumVertex - 1) {
		E = DeleteMin(H);
		Uset = Find(U, S);
		Vset = Find(V, S);
		if (Uset != Vset) {
			EdgesAccepted++;
			SetUion(S, USet, VSet);
		}
	}
}
Ejemplo n.º 25
0
int main() {

	/* Question 1. */
	puts(KBLU "\n1. Read in numbers in data 100 one by one and insert them into an initially empty heap. Print out the elements in the array (you should check the output to see if the heap order is satisfied)." RESET);

	// open file
	FILE * fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	PriorityQueue H = Initialize( 100 );
	// insert data
	int i, cur;
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintHeap( H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );


	/* Question 2. */
	puts(KBLU "\n2. Write a function to print out elements that are smaller than 15000 (not necessary in sorted order). The function should run in O(K), where K is the number of the elements you print out. " RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintSmaller( 15000, H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 3. */
	puts(KBLU "\n3. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 4. */
	puts(KBLU "\n4. Find the 30th smallest element by repeatly using DeleteMin. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );

	// first 30 smallest number
	int tmp;

	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 5. */
	puts(KBLU "\n5. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Insert( cur, H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* EXPERIMENT */
	puts(KBLU "\n6. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a 4-heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	/* Question 7. */
	puts(KBLU "\n7. Find the 30th smallest element by repeatly using DeleteMin. (4-heap)\n" RESET);

	// first 30 smallest number
	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 8. */
	puts(KBLU "\n8. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. (4-heap)\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Append( cur, H );
			BuildHeap( H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));
	puts("");

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	return 0;
}
Ejemplo n.º 26
0
/*The algorithm uses an idea similar to the standard MST algorithm*/
void TopoCentLB :: calculateMST(PartGraph *partgraph,LBTopology *topo,int *proc_mapping,int max_comm_part) {

  int *inHeap;
  double *keys;
  int count = partgraph->n_nodes;
  int i=0,j=0;

  //Arrays needed for keeping information
  inHeap = new int[partgraph->n_nodes];
  keys = new double[partgraph->n_nodes];

  int *assigned_procs = new int[count];

  hopCount = new double*[count];
  for(i=0;i<count;i++){
    proc_mapping[i]=-1;
    assigned_procs[i]=0;
    hopCount[i] = new double[count];
    for(j=0;j<count;j++)
      hopCount[i][j] = 0;
  }

  //Call a topology routine to fill up hopCount
  topo->get_pairwise_hop_count(hopCount);
	
  int max_neighbors = topo->max_neighbors();
	
  HeapNode *heap = new HeapNode[partgraph->n_nodes];
  heapMapping = new int[partgraph->n_nodes];
	
  int heapSize = 0;

  for(i=0;i<partgraph->n_nodes;i++){
    heap[i].key = 0.00;
    heap[i].node = i;
    keys[i] = 0.00;
    inHeap[i] = 1;
    heapMapping[i]=i;
  }

  //Assign the max comm partition first
  heap[max_comm_part].key = 1.00;
	
  heapSize = partgraph->n_nodes;
  BuildHeap(heap,heapSize);

  int k=0,comm_cnt=0,m=0;
  int *commParts = new int[partgraph->n_nodes];
	
  //srand(count);

  while(heapSize > 0){

    /****Phase1: Extracting appropriate partition from heap****/

    HeapNode max = extractMax(heap,&heapSize);
    inHeap[max.node] = 0;

    for(i=0;i<partgraph->n_nodes;i++){
      commParts[i]=-1;
      PartGraph::Edge wt = partgraph->edges[max.node][i];
      if(wt == 0)
	continue;
      if(inHeap[i]){
#ifdef MAX_EDGE
	if(wt>keys[i])
	  keys[i]=wt;
#else
	keys[i] += wt;
#endif
        /*This part has been COMMENTED out for optimizing the code: we handle the updation using heapMapping*/
        /*array instead of searching for node in the heap everytime*/

	//Update in the heap too
	//First, find where this node is..in the heap
	/*for(j=0;j<heapSize;j++)
	  if(heap[j].node == i)
	  break;
	  if(j==heapSize)
	  CmiAbort("Some error in heap...\n");*/
	increaseKey(heap,heapMapping[i],wt);
      }
    }
		 
    /*Phase2: ASSIGNING partition to processor*/
		
    //Special case
    if(heapSize == partgraph->n_nodes-1){ //Assign max comm partition to 0th proc in the topology
      proc_mapping[max.node]=0;
      assigned_procs[0]=1;
      continue;
    }
		
    m=0;

    comm_cnt=0;

    double min_cost=-1;
    int min_cost_index=-1;
    double cost=0;
    int p=0;
    //int q=0;

    for(k=0;k<partgraph->n_nodes;k++){
      if(!inHeap[k] && partgraph->edges[k][max.node]){
	commParts[comm_cnt]=k;
	comm_cnt++;
      }
    }

    //Optimized the loop by commenting out the get_hop_count code and getting all the hop counts initially
    for(m=0;m<count;m++){
      if(!assigned_procs[m]){
	cost=0;
	for(p=0;p<comm_cnt;p++){
	  //if(!hopCount[proc_mapping[commParts[p]]][m])
	  //hopCount[proc_mapping[commParts[p]]][m]=topo->get_hop_count(proc_mapping[commParts[p]],m);
	  cost += hopCount[proc_mapping[commParts[p]]][m]*partgraph->edges[commParts[p]][max.node];
	}
	if(min_cost==-1 || cost<min_cost){
	  min_cost=cost;
	  min_cost_index=m;
	}
      }
    }

    proc_mapping[max.node]=min_cost_index;
    assigned_procs[min_cost_index]=1;
  }

  //clear up memory
  delete[] inHeap;
  delete[] keys;
  delete[] assigned_procs;
  delete[] heap;
  delete[] commParts;
}