Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

SELECTION SORT

Group 7
Members
Lomocso, Al john
Sehwani, Nicole
Tejada Nigel Ralp
Ladrillo Kyla Dizon
Fairbanks Merielle Daye
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 ithroughlength -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 6
2
Smallest? 1
3
5
We start by searching for the smallest
element in the List. 4
Smallest?
Smallest!
6
6
2
2
Swap!
1
1
3
3
5 5
4 4
Swapped!
Smallest?
1
After the smallest element is in the first 2
position, we continue searching with the 6
second element and look for the next
smallest element. 3
Smallest! 5
4
In this special case, the next smallest
element is in the second position already.
Swapping keeps it in this position.
Swapped 1
2
Swapping keeps it in this position. 6
Smallest? 3
5
After the next smallest element is in the
second position, we continue searching 4
1
with the third element and look for the 2
next smallest element.
Smallest! 3
1
6
Swap!
2
5
Swapped Smallest? 6
3
4
Smallest? 6
3
1
5
2
4
3
6
1
2 1
3
2
6
3
5
6
4
Swap! 4
5
Smallest!
Swapped 4
6
The last two elements are in order, so no
swap is necessary
What “Swapping” means
1
2
3
4
5
6
6 TEMP
61
22
11
33
Place the first element into the 55
Temporary Variable.
TEMP 44
6
Replace the first element with the value
of the smallest element. 1
TEMP
2
6 6
Replace the third element (in this 3
example) with the Temporary Variable.
5
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