



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of the selection sort algorithm, a simple sorting technique used to arrange elements in increasing order. The algorithm's implementation, its polymorphic nature, and its efficiency analysis using big-oh notation. Selection sort is a fundamental concept in computer science, and understanding its concepts can help students grasp more complex sorting and searching algorithms.
Typology: Exams
1 / 6
This page cannot be seen from the preview
Don't miss anything!




problems.
int compareTo( Object obj )
< 0 if this < obj
== 0 if this == obj
0 if this > obj
for ( i running from 0 up to n-1 ) {
Let j = index of the smallest of a[i], a[i+1], … a[n-1];
swap a[i] with a[j];
}
public static void selectionSort( Comparable[ ] a ) {
for ( int i = 0; i < a.length; i++ ) {
int j = indexOfMin( i, a );
swap( i, j, a );
}
}
private static int indexOfMin( int start, Comparable[ ] a ) {
Comparable min = a[start];
int minIndex = start;
for ( int i = start + 1; i < a.length; i++ )
if ( a[i].compareTo( min ) < 0 ) {
min = a[i];
minIndex = i;
}
return minIndex;
}
private static void swap( int i, int j, Comparable[ ] a ) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
i j
swa
p
i j
swa
p
i j
swa
i j swap
i j swap
i j swap
3 5 11 8 15 6
3 5 6 8 15 11
3 5 6 8 15 11
3 5 6 8 11 15
8 6 11 3 15 5
3 6 11 8 15 5
the array.
of the array. E.g., some algorithms run faster if the initial array is nearly sorted.
the highest running time.
(This is very messy , so we won’t do it.)
in the worst-case to sort an array of n items using Selection Sort.
for i = 0, 1, 2, …, n-1.
element of the subarray a[i+1, …, n-1].
compareTo( ).
i=0 (n-0-1) = n-
i=1 (n-1-1) = n-
i=2 (n-2-1) = n-
…
i=n-2 (n-(n-2)-1) = 1
i=n-1 (n-(n-1)-1) = 0
n 1
i 0
T(n) = 0 + 1 + 2 + 3 + … + (n-3) + (n-2) + (n-1)
T(n) = 0 + 1 + 2 + 3 + … + (n-3) + (n-2) + (n-1)
= (1 + (n-1)) + (2 + (n-2)) + (3 + (n-3)) + …
= n + n + n + …
There are roughly (n-1)/2 pairs, each of which sums to n. Thus, the total value is roughly
n(n-1)/2. (In fact, this is exactly correct.)
2 2
n(n 1 ) n n n n
T (n)
2 2 2 2