Sort Algorithm - Selection Sort

Last updated on September 4, 2023 pm

Definition:

Selection sort is a simple comparison-based sorting algorithm that repeatedly selects the minimum element from the unsorted part of the array and places it at the beginning. It works by dividing the input array into two parts: the sorted and the unsorted portions. While straightforward, it has a time complexity of O(n^2), making it inefficient for large datasets.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class SelectionSort {
public static void main(String[] args) {
// Create an array of integers
int[] arr = {101, 34, 99, 1};

// Call the selectionSort function to sort the array
selectionSort(arr);
}

public static void selectionSort(int[] arr) {
// Iterate through the array elements
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
int minNum = arr[i];

// Find the minimum element in the unsorted part of the array
for (int j = i + 1; j < arr.length; j++) {
if (minNum > arr[j]) {
minNum = arr[j];
minIndex = j;
}
}

// Swap the minimum element with the current element (if needed)
if (minIndex != i) {
arr[minIndex] = arr[i];
arr[i] = minNum;
}
}

// Print the sorted array
System.out.println(Arrays.toString(arr));
}

}

Sort Algorithm - Selection Sort
http://hihiko.zxy/2023/09/04/Sort-Algorithm-Selection-Sort/
Author
Posted on
September 4, 2023
Licensed under