20_10

Write a C program to sort an array using Selection Sort.

Source code:

 /*The Selection Sort works by finding the smallest unsorted item in the list and swapping it with the item in the current position. The algorithm works as follows:

1. Set first position as current position.

2. Find the minimum value in the list

3. Swap it with the value in the current position

4. Set next position as current position

5. Repeat Steps 2-4 until you reach end of list 


First an array of size 10 will be taken. We will fill it by reading 10 integers. The final output will be sorted output in Ascending Order.*/


#include <stdio.h>

int main()

{

    int array[10], n=10, i, j, index, swap;


   /* Read Array Elements */

printf("Enter the array:");

    for ( i = 0 ; i < n ; i++ )

    scanf("%d", &array[i]);

    for ( i = 0 ; i < ( n - 1 ) ; i++ )

    {

    index = i;

    for ( j = i + 1 ; j < n ; j++ )

        {

        if ( array[index] > array[j] )

            index = j;

        }

      if ( index != i )

      {

        swap = array[i];

        array[i] = array[index];

        array[index] = swap;

        }

    }

printf("The sorted output in ascending order:\n");

    for ( i = 0 ; i < n ; i++ )

    printf("%d\n", array[i]);

    return 0;

}

Output:
C program to sort an array using Selection Sort


No comments:

Post a Comment

Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...