C program to sort an array in ascending and descending order using selection sort

Selection sort program in C: In this tutorial, we will learn how to sort an array in ascending and descending order using selection sort with the help of the C program? By IncludeHelp Last updated : August 03, 2023

Selection sort is the most simplest Sorting Technique, in this sorting technique first finds the smallest or largest element (depending on the order that you want to do) and swaps the smallest or largest elements with the corresponding element.

Problem statement

In this program we will read N number of elements in an One Dimensional Array and arrange all elements in Ascending and Descending Order using Data Structure Selection Sort technique.

C program to sort an array in ascending and descending order using selection sort

/*Selection Sort - C program to sort an Array 
in Ascending and Descending Order.*/
 
#include <stdio.h>
 
#define MAX 100
 
int main()
{
    int arr[MAX],limit;
    int i,j,temp,position;
     
    printf("Enter total number of elements: ");
    scanf("%d",&limit);
     
    /*Read array*/
    printf("Enter array elements: \n");
    for(i=0; i<limit; i++)
    {
        printf("Enter element %3d: ",i+1);
        scanf("%d",&arr[i]);
    }
     
    /*sort elements in Ascending Order*/
    for(i=0; i<(limit); i++)
    {
        position=i;
        for(j=i+1; j<limit; j++)
        {
            if(arr[position]>arr[j])
            {
                position=j;
            }
            if(position!=i)
            {
                temp=arr[i];
                arr[i]=arr[position];
                arr[position]=temp;                
            }
        }
    }
 
    printf("Array elements in Ascending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
     
    printf("\n");
         
    /*sort elements in Descending Order*/
    for(i=0; i<(limit); i++)
    {
        position=i;
        for(j=i+1; j<limit; j++)
        {
            if(arr[position]<arr[j])
            {
                position=j;
            }
            if(position!=i)
            {
                temp=arr[i];
                arr[i]=arr[position];
                arr[position]=temp;                
            }
        }
    }
 
    printf("Array elements in Descending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
         
    printf("\n");
     
    return 0;
}

Output

Enter total number of elements: 5 
Enter array elements: 
Enter element 1: 11 
Enter element 2: 2
Enter element 3: 1
Enter element 4: 223
Enter element 5: 4
Array elements in Ascending Order:
1 2 4 11 223
Array elements in Descending Order: 
223 11 4 2 1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.