Monday, January 24, 2011

[discussion_vu] CS301 ASSIGNMENT IDEA SOLUTIONS

A program to implement Heap Sort

#include<iostream.h>
#include<conio.h>

void restoreHup(int*,int);
void restoreHdown(int*,int,int);

void main()
{
int a[20],n,i,j,k;
printf("
Enter the number of elements to sort : ");
scanf("%d",&n);

printf("
Enter the elements :
");
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
restoreHup(a,i);
}


j=n;
for(i=1;i<=j;i++)
{
int temp;
temp=a[1];
a[1]=a[n];
a[n]=temp;
n--;
restoreHdown(a,1,n);
}

n=j;

printf("
Here is it...
");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
}



void restoreHup(int *a,int i)
{
int v=a[i];

while((i>1)&&(a[i/2]<v))
{
a[i]=a[i/2];
i=i/2;
}
a[i]=v;
}

void restoreHdown(int *a,int i,int n)
{
int v=a[i];
int j=i*2;
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
j++;
if(a[j]<a[j/2]) break;

a[j/2]=a[j];
j=j*2;
}
a[j/2]=v;
}




BY AQEEL


Idea solution

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <codecogs/computing/sort/heap.h>

int main()
{
double vals[25];
int n=25;

for (int i=0; i<n; i++) vals[i]=((double) n*rand())/RAND_MAX;

printf("\nArray to be sorted:\n");
for (int i=0; i<n; i++) printf("%3.0f ", vals[i]);

Computing::Sort::heapSort(vals, n);

printf("\nSorted array:\n");
for (int i=0; i<n; i++) printf("%3.0f ", vals[i]);
printf("\n");
return 0;
}Output:
Array to be sorted:
23 6 6 13 11 10 13 4 9 4
17 14 7 5 16 7 21 7 17 17
23 6 16 9 18
Sorted array:
4 4 5 6 6 6 7 7 7 9
9 10 11 13 13 14 16 16 17 17
17 18 21 23 23Parameters:
vals the array of values to be sorted
n the number of items in the array




*~ WS ~*
*~ Devil Jin ~*
*
Bscs 4th Semester *

--
You received this message because you are subscribed to the Google Groups "Virtual University of Pakistan" group.
To post to this group, send email to discussion_vu@googlegroups.com.
To unsubscribe from this group, send email to discussion_vu+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/discussion_vu?hl=en.

No comments:

Post a Comment

PAID CONTENT