write a program for selection sort in c & python
write a program for selection sort in c & python
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)
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
i, the inner loop finds the index of the smallest element from position i to the end.i, so the first i+1 elements are now sorted.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.
Log in or create a free account to answer this question.