Friday, August 4, 2017

Program to implement Selection Sort in C

#include <stdio.h>
void selection_sort(int a[], int k);
int main()
{
    int arr[100], n, i;
    printf("\n= = = = = = = = = = Selection Sort in C = = = = = = = = = =\n");
    printf("How many integers you wanna store..? : ");
    scanf("%d", &n);
    printf("Enter %d integers into the array:\n", n);
    for(i=0; i<n; i++)
    {
        scanf("%d",&arr[i]);
    }
    printf("Before sorting the array elements are:\n");
    for(i=0; i<n; i++)
    {
        printf("%d\t",arr[i]);
    }
    selection_sort(arr,n);
    printf("\n\nAfter sorting the array elements are:\n");
    for(i=0; i<n; i++)
    {
        printf("%d\t",arr[i]);
    }
    printf("\n= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n\n");
    return 0;
}
void selection_sort(int arr[], int k)
{
    int i, j, pos, temp;
    for (i=0; i<(k-1); i++ )
    {
        pos=i;
        for (j=i+1; j<k;j++ )
        {
            if(arr[pos]>arr[j] )
                pos=j;
        }
        if(pos!=i)
        {
            temp = arr[i];
            arr[i] = arr[pos];
            arr[pos] = temp;
        }
    }
  
}

OutPut:
manoj@ubuntu:~/cp$ gcc select_sort.c -o select_sort
manoj@ubuntu:~/cp$ ./select_sort

= = = = = = = = = = Selection Sort in C = = = = = = = = = =
How many integers you wanna store..? : 8
Enter 8 integers into the array:
4
7
6
3
5
2
8
1
Before sorting the array elements are:
4    7    6    3    5    2    8    1   

After sorting the array elements are:
1    2    3    4    5    6    7    8   
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

manoj@ubuntu:~/cp$

No comments:

Post a Comment