Selection Sort

Being Good
Jul 27, 2023

Selection Sort (Brute Force) — Sorting by repeated selection.

Sorting technique:

  • Find smallest element and put in first place
  • Find next smallest element and put in second place
  • Repeat till end of list

Pseudocode:

Javacode:

package sorting;

public class SelectionSort {

public int[] sort(int[] array){
System.out.println("Starting sort");
int length = array.length;
for (int i = 0; i < length; i++) {
int minvalue = array[i];
int minindex = i;
for (int j = i+1; j < length; j++) {
if (array[j] < minvalue) {
minvalue = array[j];
minindex = j;
}
}
swap(array, i, minindex);
}
return array;
}

private void swap (int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}

}

Asymptotic analysis

Theta(n) = n squared

O(n) = n squared

Note: Please “follow” and leave a “clap” :-)

--

--