Algorithm - Selection Sort

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.

The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.

Algorithm is not suitable for large data sets.

Solution:

public class SelectionSort {

    public static int[] sortNumbers(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[index]) {
                    index = j;
                }
            }

            int smallerNumber = arr[index];
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
        return arr;
    }

    public static void main(String a[]) {
        int[] arr1 = {8, 28, 40, 2, 7, 6, 25, 17, -2};
        int[] arr2 = sortNumbers(arr1);
        for (int i = 0; i < arr2.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(arr2[i]);
        }
    }
}

Result:
-2, 2, 6, 7, 8, 17, 25, 28, 40

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

Dependencies vs Dev Dependencies in Flutter

What's new in android 14?