0% found this document useful (0 votes)
7 views1 page

Selection Sort

The document provides an implementation of the selection sort algorithm in C++. It discusses the time complexity, which is O(n^2) for both best and worst cases, and notes that the space complexity is O(1) since it is an in-place sorting algorithm. Additionally, it outlines use cases where selection sort is advantageous, such as minimizing swaps and handling small arrays.

Uploaded by

Anupam roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Selection Sort

The document provides an implementation of the selection sort algorithm in C++. It discusses the time complexity, which is O(n^2) for both best and worst cases, and notes that the space complexity is O(1) since it is an in-place sorting algorithm. Additionally, it outlines use cases where selection sort is advantageous, such as minimizing swaps and handling small arrays.

Uploaded by

Anupam roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <bits/stdc++.

h>
using namespace std;

void selectionSort(vector<int>& arr, int n)


{
for(int i = 0; i < n - 1; i++) {
int minIndex = i;

// Find the minimum element in the unsorted part


for(int j = i + 1; j < n; j++) {
if(arr[minIndex] > arr[j])
minIndex = j;
}

// Swap the found minimum element with the first element


swap(arr[i], arr[minIndex]);
}
}

/*
Complexity Analysis:

- **Best Case Time Complexity: O(n^2)**


- Even if the array is already sorted, selection sort still scans all elements to find the minimum, making it ineffic

- **Worst Case Time Complexity: O(n^2)**


- When the array is sorted in reverse order, selection sort still makes the same number of comparisons and swaps as i

- **Space Complexity: O(1)**


- Selection sort is an in-place sorting algorithm. It does not require extra space beyond a few variables.

Use Cases:
- **When the number of swaps should be minimized** (Selection sort makes at most `n-1` swaps, unlike Bubble Sort which
- **Useful for small arrays** where efficiency is not a concern.
- **Good when writing to memory is costly**, as it minimizes the number of swaps.
*/

You might also like