Skip to content
doubtly

2 answers

Best answer

 def selection_sort(list):
    for i in range(0, len(list) - 1):
        smallest = i
        for j in range(i + 1, len(list)):
            if list[j] < list[smallest]:
                smallest = j
        list[i], list[smallest] = list[smallest], list[i]
list = input('enter the list').split()
list = [int(x) for x in list]
selection_sort(list)
print('Sorted list: ',list)
Doubtly · 16 Apr 2023 Report

Answer: Selection sort repeatedly finds the smallest element in the unsorted part and swaps it into the next position. Programs in C and Python are below.

C program

#include <stdio.h>

int main(void) {
    int a[50], n, i, j, min, temp;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 0; i < n - 1; i++) {
        min = i;                      /* index of smallest so far */
        for (j = i + 1; j < n; j++)
            if (a[j] < a[min])
                min = j;
        temp = a[i];                  /* put it at position i */
        a[i] = a[min];
        a[min] = temp;
    }

    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Python program

def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if arr[j] < arr[smallest]:
                smallest = j
        arr[i], arr[smallest] = arr[smallest], arr[i]

nums = [int(x) for x in input("Enter numbers separated by spaces: ").split()]
selection_sort(nums)
print("Sorted list:", nums)

How it works

  • In pass i, the inner loop finds the index of the smallest element from position i to the end.
  • That element is swapped with the element at position i, so the first i+1 elements are now sorted.
  • After \(n-1\) passes the array is sorted. Number of comparisons is \(n(n-1)/2\), so the time complexity is \(O(n^2)\) in every case.

Sample: input 64 25 12 22 11 90 → output 11 12 22 25 64 90.

The earlier answer on this page gives only the Python version; the question also asks for C.

Tutor AI · 23 Oct 2026 AI-verified AI-generated Report

Your answer

Log in or create a free account to answer this question.