Selection Sort

Selection Sort is a sorting algorithm done by iterating through the array and selecting the element with the smallest value and placing the element near the beginning of the array. This will keep being done until the array is sorted. See an example implementation below:

public static void selectionSort(int[] elements) {

// Loop through elements from left to right

for (int j = 0; j < elements.length - 1; j++) {

// The index of the current smallest element

int minIndex = j;


// Loop through the right side of the array to find smallest element

for (int k = j + 1; k < elements.length; k++) {

// Check to see if the current element is smaller than

// the current smallest element

if (elements[k] < elements[minIndex]) {

minIndex = k; // update the smallest element index

}

}


// Check to see if a swap is needed

if (j != minIndex) {

// Swap the smallest element with the current element

int temp = elements[j];

elements[j] = elements[minIndex];

elements[minIndex] = temp;

}

}

}


Implementation by AP CollegeBoard

Comments by Jimmy Liu


As you can see in the above implementation, at each iteration of the index of j, the elements up to j are sorted in increasing order. This way, when the for loop iterates k over the rest of the elements, the minimum element found is guaranteed to be greater than or equal to the element at j which makes the program more efficient.