0% found this document useful (0 votes)
137 views

Selection Sort

Selection sort is an algorithm that iterates through an array and finds the smallest element, swapping it with the first element. It then finds the next smallest element, swapping it with the second, and continues until the array is fully sorted. The algorithm sets the first element as the minimum, searches for the actual minimum, and swaps the first element with it. It then sets the second element as the new minimum and repeats this process until the array is sorted. The C code implementation demonstrates taking user input for the array size and elements, performing the selection sort, and outputting the sorted array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Selection Sort

Selection sort is an algorithm that iterates through an array and finds the smallest element, swapping it with the first element. It then finds the next smallest element, swapping it with the second, and continues until the array is fully sorted. The algorithm sets the first element as the minimum, searches for the actual minimum, and swaps the first element with it. It then sets the second element as the new minimum and repeats this process until the array is sorted. The C code implementation demonstrates taking user input for the array size and elements, performing the selection sort, and outputting the sorted array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Selection Sort in C

Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates
through the array and finds the smallest number in the array and swaps it with the first element
if it is smaller than the first element. Next, it goes on to the second element and so on until all
elements are sorted.

Algorithm for Selection Sort:

Step 1 − Set min to the first location

Step 2 − Search the minimum element in the array

Step 3 – swap the first location with the minimum value in the array

Step 4 – assign the second element as min.

Step 5 − Repeat the process until we get a sorted array.

Code for Selection Sort:

#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%d", a[i]);
return 0;
}

Output:
Enter number of elements
4
Enter 4 numbers
4
2
7
1
Sorted Array
1
2
4
7

You might also like