DS Practical Slip 5 Q B

C Program to Sort n Elements in Ascending Order Using Selection Sort

Selection Sort is a simple sorting technique in C where the smallest element is repeatedly selected and placed at the beginning of the array. This program is student-friendly and easy to understand.


📝 Problem Statement

B) Write a ‘C’ program to accept and sort n elements in ascending order using Selection sort method.


💡 Logic (Simple Student-Friendly Steps)

  1. Accept the number of elements n.
  2. Read n elements into an array.
  3. Use two nested loops:
    • Outer loop selects the current index i.
    • Inner loop finds the minimum element in the unsorted portion of the array.
  4. Swap the minimum element with the element at index i.
  5. Repeat until the array is completely sorted.
  6. Print the sorted array.

👉 Selection sort works by repeatedly finding the minimum element and placing it at the correct position.


💻 Source Code (Simple Version)

#include <stdio.h>

int main()
{
    int arr[100], n, i, j, minIndex, temp;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter elements:\n");
    for(i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    // Selection Sort
    for(i = 0; i < n-1; i++)
    {
        minIndex = i;
        for(j = i+1; j < n; j++)
        {
            if(arr[j] < arr[minIndex])
                minIndex = j;
        }

        // Swap
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }

    printf("Sorted array in ascending order:\n");
    for(i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }

    return 0;
}

🖥️ Sample Output

Enter number of elements: 5
Enter elements:
50 20 40 10 30
Sorted array in ascending order:
10 20 30 40 50

🎓 Viva Questions with Answers

1. What is Selection Sort?

Selection Sort is a sorting algorithm that repeatedly selects the smallest element and places it at the correct position.

2. What is the time complexity of Selection Sort?

O(n²) in all cases (best, average, and worst).

3. Is Selection Sort stable?

No, it is not stable because swapping may change the relative order of equal elements.

4. Does Selection Sort require extra space?

No, it is an in-place sorting algorithm.

5. How does it differ from Bubble Sort?

Selection Sort selects the minimum element in each iteration, while Bubble Sort repeatedly swaps adjacent elements.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top