﻿ Algorithm for Selection Sort || CseWorld Online

# Algorithm for Selection Sort

```Step 1: Repeat For J = 0 to N-1
Step 2: Set MIN = J
Step 3: Repeat For K = J+1 to N
Step 4: If (A[K] < A[MIN]) Then
Step 5: Set MIN = K
[End of If]
[End of Step 3 For Loop]
Step 6: Interchange A[J] and A[MIN]
[End of Step 1 For Loop]
Step 7: Exit```

## How Selection Sort works

In the first pass, the smallest element found is 1, so it is placed at the first position, then leaving first element, smallest element is searched from the rest of the elements, 3 is the smallest, so it is then placed at the second position. Then we leave 1 and 3, from the rest of the elements, we search for the smallest and put it at third position and keep doing this, until array is sorted

## Program

```void selectionSort(int a[], int size)
{
int i, j, min, temp;
for(i=0; i < size-1; i++ )
{
min = i; //setting min as i for(j=i+1; j < size; j++)
{
if(a[j] < a[min]) //if element at j is less than element at min position
{
min = j; //then set min as j
}
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}```