# C program to sort elements in an array using selection sort

Selection sort algorithm finds the smallest element in the list and put it in the first position during first pass. Then finds the second smallest element in the list and put it in the second position in pass 2. In the ith pass, selects the element with the lowest key, among A[i], . . . , A[n], and swaps it with A[i]. As a result, after i passes, the i lowest records will occupy A[1] , . . . , A[i], in sorted order. Following example illustrates selection sort. Selections sort has a time complexity of BigO of n square and note that selection sort doesn’t make comparisons more than O(n). It is the most used algorithm when auxiliary memory is used. As that has got fixed number of comparisons.# Source code:

#include<stdio.h> void selectsort(int [], int); int main() { int arr[50], n, key, index; printf("How many elements do you want to create the array with?(max 50): "); fflush(stdout); scanf("%d", &n); puts("Enter the array elements one by one \n"); for (index = 0; index < n; index++) scanf("%d", &arr[index]); //Step 1 selectsort(arr, n); //Step 2 printf("\n The elements after sorting are...\n"); for (index = 0; index < n; index++) printf("%d ", arr[index]); //Step 3 return 0; } void selectsort(int numbers[], int array_size) { int i, j; int min, temp; for (i = 0; i < array_size-1; i++) { min = i; for (j = i+1; j < array_size; j++) { if(numbers[j] < numbers[min]) min = j; } if(min != i) { temp = numbers[i]; numbers[i] = numbers[min]; numbers[min] = temp; } } }

# Sample test cases:

1. How many elements do you want to create the array with?(max 50): 5 Enter the array elements one by one 445 78 23 0 3 The elements after sorting are… 0 3 23 78 445 2. How many elements do you want to create the array with?(max 50): 4 Enter the array elements one by one 32 98 0 1 The elements after sorting are… 0 1 32 98## Explanation:

Step 1: The elements of an array are read from the user using scanf() function.
Step 2: The function selectsort(arr,n) is called from the main program which sorts the elements of an array.
Step 3: After sorting the elements are printed on the output screen using printf() function.

Explore C Programs:C Programs More Insights:Sorting