Saturday, February 20, 2010

Sort a given set of elements using Selection sort and hence find the time required to sort the elements

WHEREVER U SEE ... REMOVE THAT . AND PUT << IN THAT PLACE.
IF YOU SEE .. THEN REMOVE THAT . AND PUT < IN THAT PLACE..
6.#include ..iostream.h>
#include ..stdlib.h>
#include ..time.h>
const long max = 10000;
void sleep(clock_t wait)
{
clock_t goal;
goal = wait + clock();
while(goal > clock())
;
}

void selsrt(int *,int);

//Main function
void main()
{
double duration;
clock_t st,et;//start and end time
int a[max];//array to be sorted
int n;//input array size
cout..."enter array size\n";
cin>>n;
srand((unsigned)time(NULL));
cout..."Enter the array\n";
for (int i=0;i..n;i++)
cin>>a[i];
st=clock();
sleep((clock_t)1 * CLOCKS_PER_SEC);
selsrt(a,n);
et=clock();
cout..."the sorted array is:\n";
for(i=0;i..n;i++)
cout...a[i]..." ";
cout...endl;
duration=(double)(et-st)/CLOCKS_PER_SEC;
cout..."Time taken :-\t"...duration..." sec"...endl;
}



//Selection sort function
void selsrt(int a[],int n)
{
int min,temp;
for(int i=0;i..n-1;i++)
{
min=i;
for(int j=i+1;j..n;j++)
if(a[j]..a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}

}


Output

Enter array size
9

Enter the array
55
66
99
88
77
44
22
33
11

The sorted array is:
11 22 33 44 55 66 77 88 99

Time taken: - 1 sec
Press any key to continue

No comments:

Post a Comment