# What Is Selection Sorting in Data Structure?

//

Heather Bennett

What Is Selection Sorting in Data Structure?

The selection sort algorithm is one of the simplest sorting algorithms used in computer science. It works by repeatedly finding the minimum element from the unsorted part of an array and placing it at the beginning. This process is then repeated for the remaining elements until the entire array is sorted.

## How Does Selection Sorting Work?

The selection sort algorithm divides the given array into two parts – a sorted part and an unsorted part. Initially, the sorted part is empty, and the unsorted part contains all the elements.

To perform selection sorting, follow these steps:

• Step 1: Set the first element of the array as the minimum.
• Step 2: Iterate through the remaining unsorted elements.

• If any element is smaller than the current minimum, update the minimum to that element.
• Step 3: Swap the minimum element with the first element of the unsorted part.
• Step 4: Move to the next position and repeat steps 1-3 until all elements are sorted.

## An Example of Selection Sorting

To better understand how selection sorting works, let’s consider an example.

We have an array with six elements: [5, 2, 9, 1, 7, 3].

Note: The indices start from zero.

First iteration:

Initially, the minimum element is at index 0 (value: 5).

• Compare the minimum element with the rest of the array.
• The element at index 1 (value: 2) is smaller than the current minimum.
• Update the minimum to index 1.

Swap the elements at indices 0 and 1:

```[2, 5, 9, 1, 7, 3]
```

Second iteration:

The minimum element is at index 1 (value: 5).

• Compare the minimum element with the rest of the array.
• No elements smaller than the current minimum are found.
• The minimum remains unchanged.

No swap is needed in this iteration.

Third iteration:

The minimum element is at index 3 (value: 1).

• The element at index 5 (value:3) is smaller than the current minimum.
• Update the minimum to index 5.
• Swap the elements at indices 3 and 5:

`[2,5,9,3,7,1] => [2,5,9,1,7,3] `

## The Final Sorted Array:

`[1,2,3,5,7,9]`

## Advantages and Disadvantages of Selection Sorting:

• Simple to understand and implement.
• Works well for small-sized arrays.
• Has a time complexity of O(n^2), where n is the number of elements in the array.