# Selection Sort

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

1. Find the minimum value in the list.
2. Swap it with the value in the current position.
3. 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);
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

It is used when:

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

### Other Sorting Algorithms :-

#### Group Anagrams LeetCode Solution

Given an array of strings strs, group the anagrams together. You can return the answer…

#### 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,…

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.😎

Scroll to Top