Saturday 15 September 2012

Write a c program for selectioon 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 eements. If the 0th element is found to be greater than the compared element then they are interchanged.

        Algorithm:
1)      Start
2)      Initiliaze the variables I,j,temp and arr[]
3)      Read the loop and check the condition. If the condition is true print the array elements and increment the I value. Else goto step 4
4)      Read the loop and check the condition. If the condition true then goto next loop.
5)      Read the loop and check the condition. If the condition true then goto if condition
6)      If the condition if(arr[i]>arr[j]) is true then do the following steps
i)                    temp=arr[i]
ii)                  arr[i]=arr[j]
iii)                arr[j]=temp
7)      increment the j value
8)      perform the loop operation for the displaying the sorted  
elements.
9)      print the sorted elements
10)  stop

 Program:
#incude<stdio.h>
#incude<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();
}
Sampe input & 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
Concusion: this program is error free
VIVA QUESATIONS
1)  The complexity of the section  sort algorithm ?
Ans:  O(n2)
2) 1) 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)

No comments:

Post a Comment