Selection sort in Java

 Selection sort in Java

Selection sort is an algorithm for sorting an array by repeatedly selecting the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two sub-arrays in a given array.



  1. The sub-array which is already sorted.
  2. Remaining sub-array which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted sub-array is picked and moved to the sorted sub-array.


Here is an example of how you might implement selection sort in Java:


class SelectionSort {

  public static void sort(int[] array) {

    int n = array.length;

    for (int i = 0; i < n - 1; i++) {

      int minIndex = i;

      for (int j = i + 1; j < n; j++) {

        if (array[j] < array[minIndex]) {

          minIndex = j;

        }

      }

      int temp = array[minIndex];

      array[minIndex] = array[i];

      array[i] = temp;

    }

  }

}


You can then use the sort method to sort an array as follows:

int[] array = {4, 3, 2, 1};
SelectionSort.sort(array);
System.out.println(Arrays.toString(array)); // Outputs [1, 2, 3, 4]

Post a Comment

0 Comments