2. List of contents
● Introduction
● Example w/ illustrating figures
● Algorithm
● implementation (Java, C++, Python)
● Performance Runtime
○ Best, Average and worst cases.
● Execution
● Other Notes
3. Introduction
● sorts an array by repeatedly finding the minimum element (considering ascending
order) from 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 ,the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray .
4. Example
arr[] = 19, 5, 7, 12
// Find the minimum element in arr[0...3]
// and place it at beginning
5, 19, 7, 12
// Find the minimum element in arr[1...3]
// and place it at beginning of arr[1...3]
5, 7, 19, 12
// Find the minimum element in arr[2...3]
// and place it at beginning of arr[2...3]
5, 7, 12, 19
5. Algorithm .
● Let the min : 0
● Search the minimum
● Swap with value at location min
● Increment min
● Repeat until is sorted
7. C++ .
void selectionSort(int a[], int len)
{
int min, i, j ;
for(i=0; i<len-1; i++)
{
min = i ;
for(j=i+1; j<len; j++)
{
if(a[j] < a[min])
min = j ;
}
swap(&a[i], &a[min]) ;
}
}
8. JAVA .
void sort(int a[])
{
int len = a.length, min;
for (int i = 0; i < len-1; i++)
{
min = i;
for (int j=i+1; j<len; j++)
if (a[j] < a[min])
min = j;
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
9. Python .
def selectionSort(a):
for i in range(len(a)):
min = i
for j in range(i+1, len(a)):
if a[min] > a[j]:
min = j
a[i], a[min] = a[min], a[i]
10. Performance Runtime
● Time complexity Θ(n2
) .
● it never makes more than O(n) swaps =>
can be useful when memory write is a costly operation .