C program to implement selection sort using recursion

Here, we are going to learn how to implement selection sort using recursion in C language?
Submitted by Nidhi, on August 26, 2021

Problem Solution:

Create an array of integers with 5 items, then sort the array elements using selection sort with the recursion.

Program:

The source code to implement selection sort using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to implement selection sort
// using recursion

#include <stdio.h>

void SelectionSort(int arr[], int i, int j, int len, int flag)
{
    if (i < len - 1) {
        if (flag)
            j = i + 1;

        if (j < len) {
            if (arr[i] > arr[j]) //Swap numbers
            {
                arr[i] = arr[i] + arr[j];
                arr[j] = arr[i] - arr[j];
                arr[i] = arr[i] - arr[j];
            }
            SelectionSort(arr, i, j + 1, len, 0);
        }
        SelectionSort(arr, i + 1, 0, len, 1);
    }
}

int main()
{
    int arr[] = { 23, 10, 46, 21, 75 };
    int i = 0;

    printf("Array before sorting: \n");
    for (i = 0; i < 5; i++)
        printf("%d  ", arr[i]);

    SelectionSort(arr, 0, 0, 5, 1);

    printf("\nArray after sorting: \n");
    for (i = 0; i < 5; i++)
        printf("%d  ", arr[i]);

    printf("\n");

    return 0;
}

Output:

Array before sorting: 
23  10  46  21  75  
Array after sorting: 
10  21  23  46  75

Explanation:

Here, we created two functions SelectionSort() and main(). The SelectionSort() is a recursive function, which is used to sort array elements in ascending order.

In the main() function, we created an array of integers arr with 5 elements. Then we sorted the the array using SelectionSort() function.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




© https://www.includehelp.com some rights reserved.