Here, We will discuss about selection sort in C, their algorithm, implementation code in C, time and space complexity and their advantages.

**What is Selection Sort?**

**Selection Sort **is an in-place sorting algorithm. It works well on small files. It is used for storing the files with very large values and small keys.

The algorithm is based on the idea of finding the minimum element in an unsorted array and then putting it in its correct position in a sorted array.

This sorting algorithm is called selection sort because it repeatedly selects the smallest element.

It is easy to implement for small files.

**Selection Sort Algorithm**

- Find the minimum value in the list.
- Swap it with the value in the current position.
- Repeat this process for all elements until the entire array is sorted.

**Implementation of Selection Sort**

**Program Code in C :-**

```
#include<stdio.h>
//function to swap the position of two elements
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void selectionsort(int arr[], int n)
{
for(int i=0; i<n-1; i++)
{
int min = i;
for(int j=i+1; j<n; j++)
{
if(arr[j] < arr[min])
min = j;
}
swap(&arr[min], &arr[i]);
}
}
//function to print an array
void printarray(int arr[], int n)
{
for(int i=0; i<n; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
//Driver Code
int main()
{
int data[] = {3, 4, 1, 5, 2};
int n = sizeof(data)/sizeof(data[0]);
selectionsort(data, n);
printf("Sorted Array : ");
printarray(data, n);
}
```

Code language: C++ (cpp)

**Output :-**

`Sorted Array : 1 2 3 4 5`

Code language: JavaScript (javascript)

**Time and Space Complexity of Selection Sort**

Time Complexity | |

Worst Case | O(n^{2}) |

Best Case | O(n^{2}) |

Average Case | O(n^{2}) |

Space Complexity | |

Worst Case | O(1) |

**Advantages**

It is used when:

- a small list to be sorted.
- The cost of swapping does not matter.
- checking all the elements is compulsory.
- cost to writing to a memory matter like in flash memory.

### Other Sorting Algorithms :-

### Related:

#### Group Anagrams LeetCode Solution

#### Insertion Sort

Here, We will learn about insertion sort in C, their algorithm, implementation code in C,…

#### Counting Sort

Here, We will discuss about Counting Sort in C, their algorithm, implementation code in C,…

#### Radix Sort

Here, We will discuss about Radix Sort in C, their algorithm, implementation code in C,…

#### Heap Sort

Here, We will discuss about Heap Sort in C, their algorithm, implementation code in C,…

#### Bucket Sort

Here, We will discuss about Bucket Sort in C, their algorithm, implementation code in C,…

*Want to Contribute*:-

If you like “**To The Innovation**” and want to contribute, you can mail your articles to ๐ง **contribute@totheinnovation.com**. See your articles on the main page and help other coders.๐