You are on page 1of 29

SELECTION SORT

Description

A sorting technique that is typically used for


sequencing small lists.
 The Selection Sort searches (linear search) all of the

elements in a list until it finds the smallest element. It


“swaps” this with the first element in the list. Next it
finds the smallest of the remaining elements, and
“swaps” it with the second element.
The Selection Sort Algorithm

 For each index position i


– Find the smallest data value in the array
from positions i through length - 1, where
length is the number of data values
stored.

– Exchange (swap) the smallest value with


the value at position i.
A Selection Sort Example

Smallest? 6
2
1
We start by searching for the
smallest element in the List.
3
5
4
6
Smallest? 2
1
3
5
4
6
2
Smallest! 1
3
5
4
6
2
Swap! 1
3
5
4
1
2
Swapped! 6
3
5
4
1
Smallest? 2
6
After the smallest element is in the first 3
position, we continue searching with
the second element and look for the 5
next smallest element. 4
1
Smallest! 2
6
In this special case, the next smallest 3
element is in the second position
already. Swapping keeps it in this 5
position.
4
1
Swapped 2
6
Swapping keeps it in this 3
position.
5
4
1
2
Smallest? 6
3
After the next smallest element is in the
second position, we continue searching
5
with the third element and look for the 4
next smallest element.
1
2
6
Smallest! 3
5
4
1
2
6
Swap! 3
5
4
1
2
3
Swapped 6
5
4
1
2
3
Smallest? 6
5
4
1
2
3
6
Smallest? 5
4
1
2
3
6
5
Swap! 4
1
2
3
6
5
Smallest! 4
1
2
3
4
5
Swapped 6
1
2
3
4
The last two elements are in order, so 5
no swap is necessary 6
What “Swapping” means

TEMP 6
6 2
1
3
Place the first element into the 5
Temporary Variable.
4
TEMP 1
6 2
1
3
Replace the first element with the value
5
of the smallest element. 4
TEMP 1
6 2
6
3
Replace the third element (in this 5
example) with the Temporary Variable.
4
Code for Minimum

public static intfindMinimum(int[] list, int first){


intminIndex= first;
for (int index = first + 1; index < list.length;
index ++){
if (list[index] < list[minIndex])
minIndex= index ;
returnminIndex;
}
}
Code for Swap

public static void swap(int[] list, int x, int y)


{
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
Source Code

public static voidselectionSort(int[] list){


for (int index = 0; index < list.length -1; index
++){
intminIndex=findMinimum(list, index );
if (minIndex!= index );
swap(list, index , minIndex);
}
}
for i ← 1 to n-1 do
min j ← i;
min x ← A[i]
for j ← i + 1 to n do
If A[j] < min x then
min j ← j
min x ← A[j]
A[min j] ← A [i]
A[i] ← min x

You might also like