Skip to content
This repository has been archived by the owner on Apr 1, 2021. It is now read-only.

Added c++ implementation for selection-sort #1103

Merged
1 commit merged into from
Jun 8, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions Algorithms-Selection-Sort.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Algorithm Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1. The subarray which is already sorted.
2. Remaining subarray which is unsorted.
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1. The subarray which is already sorted.
2. Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

Expand All @@ -22,9 +22,43 @@ arr[] = 64 25 12 22 11
11 12 22 25 64

# Placing the minimum element in arr[3...4] in the beginning
11 12 22 25 64
11 12 22 25 64
```

#### C++ Implementation

```c++
void selection_sort(int array[], int n)
{
// Contains index of minimum element in unsorted subarray
int min_index;

// Move boundary of unsorted subarray
for(int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted subarray
min_index = i;
for(int j = i+1; j < n; j++)
{
// If present element is less than element at min_index
// Then change min_index to present index
if(array[j] < array[min_index])
{
min_index = j;
}
}

// Swap the element at min_index with the first element
int temp;
temp = array[min_index];
array[min_index] = array[i];
array[i] = temp;
}
}
```

:rocket: [Run Code](https://repl.it/CZa0)

#### Python Implementation

```python
Expand Down