Saturday, December 17, 2011

Selection sorting

Q. Write a C program to to sort a list of elements using selection sort method.

Ans.

/*program to demonstration of selection method*/
#include<stdio.h>
#include<conio.h>
#define SIZE 10
int main()
{
 int i,j,min,temp;
 int arr[SIZE];
 for(i=0; i<SIZE; i++)
 {
  printf("Enter element : ");
  scanf("%d",&arr[i]);
 }
 for(i=0; i<SIZE; i++)
 {
   min=i;
   for(j=i+1; j<SIZE; j++)
     if(arr[j]<arr[min])
        min=j;
     temp=arr[i];
     arr[i]=arr[min];
     arr[min]=temp;
 }
 printf("After selection sort the elements:\n");
 for(i=0; i<SIZE; i++)
    printf("%d\t",arr[i]);
 getch();
 return 0;
}

Output:-

Enter element : 21
Enter element : 3
Enter element : 45
Enter element : 87
Enter element : 72
Enter element : 14
Enter element : 54
Enter element : 75
Enter element : 44
Enter element : 5

After selection sort the elements :

    No comments:

    Post a Comment