Wednesday, July 26, 2023

Selection Sort Using C programming.

Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list. 

The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first element of the unsorted part. This process is repeated for the remaining unsorted portion until the entire list is sorted. 

Souce Code:-

#include<stdio.h>

void SelectionSort(int a[], int n) {
    int i, j, small, temp;
    for (i=0; i<n-1; i++){
        small = i;
        for(j=i+1; j<n; j++){
            if (a[j] < a[small]){
                small = j;
            }
        }
        temp = a[i];
        a[i] = a[small];
        a[small] = temp;
    }
}

int main() {
    int n;
    printf("Enter the length of the array : ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter the elements : ");
    for (int i=0; i<n; i++){
        scanf("%d", &arr[i]);
    }
    SelectionSort(arr, n);
    printf("The sorted array is :\n");
    for (int i=0; i<n; i++){
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:-
Enter the length of the array : 5 Enter the elements : 7 3 9 4 1 The sorted array is : 1 3 4 7 9

No comments:

Post a Comment

Selection Sort Using C programming.

Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the un...