Monday 20 December 2010

Write a c program for selection sort

Description:


This is the simplest method of sorting. In this method, to sort the data in ascending order, the 0th element is compared with all other elements. If the 0th element is found to be greater than the compared element then they are interchanged.

Program:

#include<stdio.h>
#include<conio.h> 
void main()
 {
int arr[5]={25,17,31,13,2};
Int I,j,temp;
clrscr();
printf(“selection sort\n”);
printf(“\n array before sorting:\n”);
for(i=0;i<=3;i++)
printf(“%d\t,arr[i]”);

for(i=0;i<=3;i++)
{
for(j=j+1;j<=4;j++)
   {
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

}


}

printf(“\n\n array after sortong:\n”);
for(i=0;i<=4;i++)
printf(“%d\t”,arr[i]);
getch();
}

Output:

1)  Section sort
Array before sorting:
25  17 31 13   2
Array after sorting:
2  13  17  25  31

2)  section sort
Array before sort
25  31 30 12  1
Array after sort
1  12   25 30  31


More Explanation:

In a list with n elements, we need n-1 sort passes to order the list.With each sort pass, we increase the size of the sorted list by one (and decrease the size of the unsorted list by one).The algorithm finds the smallest value in the unsorted list and swaps it with the first value in the unsorted list. Then, the barrier moves to include that item in sorted list.In a selection sort, the algorithm divides a list into two sub-lists – one sorted and one unsorted. An imaginary barrier separates the two lists.





VIVA QUESTIONS

1) The complexity of the section sort algorithm ? Ans: O(n2) 

2) Drawback of the binary tree ? 
Ans: Additional space is required for building the tree 

3) The complexity of the heap sort algorithm ?

Ans: O(n og n)






Data structures using Java

No comments:

Post a Comment