Selection Sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
Working of Selection Sort
- Set the first element as
minimum
. - Compare
minimum
with the second element. If the second element is smaller thanminimum
, assign the second element asminimum
.
Compareminimum
with the third element. Again, if the third element is smaller, then assignminimum
to the third element otherwise do nothing. The process goes on until the last element. - After each iteration,
minimum
is placed in the front of the unsorted list. - For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all the elements are placed at their correct positions.
Selection Sort Code in Java
// Selection sort in Java
import java.util.Arrays;
class SelectionSort {
void selectionSort(int array[]) {
int size = array.length;
for (int i = 0; i < size - 1; step++) {
int min_idx = i;
for (int j = i + 1; i < size; i++) {
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
// put min at the correct position
int temp = array[step];
array[step] = array[min_idx];
array[min_idx] = temp;
}
}
// driver code
public static void main(String args[]) {
int[] data = { 20, 12, 10, 15, 2 };
SelectionSort ss = new SelectionSort();
ss.selectionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}
No comments