Video

Latest

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.


selection sort


Working of Selection Sort

  1. Set the first element as minimum.
    Selection Sort Steps
    Select first element as minimum
  2. Compare minimum with the second element. If the second element is smaller than minimum, assign the second element as minimum.

    Compare minimum with the third element. Again, if the third element is smaller, then assign minimum to the third element otherwise do nothing. The process goes on until the last element.
    Selection Sort Steps
    Compare minimum with the remaining elements
  3. After each iteration, minimum is placed in the front of the unsorted list.
    Selection Sort Steps
    Swap the first with minimum
  4. 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 Steps
    The first iteration
    Selection sort steps
    The second iteration
    Selection sort steps
    The third iteration
    Selection sort steps
    The fourth iteration

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