• # SelectionSort in JAVA

Today, I will be show another comparative sorting algorithm known as Selection Sort. Selection sort works by finding a smaller element downstream from the current element and swapping the two per element of an array.

### Setup

``````# Given an array:
# [9, 47, 38, 5, 40, 99, 3]
# Resultant array:
# [3, 5, 9, 38, 40, 47, 99]``````

### Time & Space

As with insertion sort, selection sort also has the time complexity of O(n^2). The worse case scenario is when the array is sorted in the reversed order of the desired order. In this case, a swap will take place for each iteration. The space complexity of this algorithm is O(1) because this can be done in-place.

``````public static void selectionSort(int[] arr) {
int n = arr.length;
if (n == 0 || n == 1) return;

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

for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[i_min]) {
i_min = j;
}
}

int temp = arr[i];
arr[i] = arr[i_min];
arr[i_min] = temp;
}
}``````
• ## BinaryTree PreOrder Traversal in JAVA

PreOrder traversal is very similar to in-order traversal in terms of code. The idea behind pre-order traversal is to do all the processing before visiting the left subtree ...

• ## Next Greater Element in Linear Time in JAVA

This is my implementation of the algorithm for that gets the next greater element than the current element in linear time. For elements with no next greater element, match ...

• ## BinaryTree VerticalOrder Traversal in JAVA

This is my implementation of the BinaryTree vertical order traversal. Vertical order traversal is an algorithm that groups all nodes with the same horizontal distance toget...

• ## Check if Array is in BST PreOrder Form in JAVA

This is my recursive implementation of the algorithm that checks if a given Array is in BinarySearchTree PreOrder form. The idea behind this algorithm is to start with the ...

• ## BinaryTree Maximum Sum Path in JAVA

This is my implementation of the algorithm on finding the maximum sum path of a BinaryTree. The path does not have to start from the root node and does not have to end on a...