Selection Sort Explained and Implemented with Examples in Java | Sorting Algorithms | Geekific

preview_player
Показать описание

In the second video of our sorting algorithms series, we are going to tackle, explain and implement a new way of sorting. This technique goes by the Selection Sort algorithm.

Timestamps:
00:00 Introduction
00:55 Sorting an array using Selection Sort!
03:45 Selection Sort Implementation
07:35 Putting our Code to the Test
08:26 Selection Sort and Streams
09:57 Thanks for Watching!

If you found this video helpful, check other Geekific uploads:

#Geekific #SortingAlgorithms #SelectionSort #Java
Рекомендации по теме
Комментарии
Автор

Hello Geeks! Hope you found this video helpful!
Thanks to "bob mwangi" in the comments below, a small correction at around 8:38 is needed! The " i " value is not being compared, hence the second IntStream should start at " i " instead of " i + 1 ".
Alternatively, we can provide a starting value to our reduce function and set it to " i " (code snippet: int minIndex = IntStream.range(i + 1, arr.length)
.reduce(i, (left, right) -> < 0 ? left : right)). Cheers :)

geekific
Автор

You can also swap values without 3rd variable using sum method:

arr[0] = arr[0]+arr[minIndex],
arr[minIndex] = arr[0] - arr[minIndex],
arr[0] = arr[0] - arr[mnIndex]

MaximusRichterson
Автор

Hi, you are swapping the value at index i with what is the smallest in the array(checking from i+1 - end); The first range starts at 0, while the second one starts at i+1, this means the code does not check the value initially at index 0 before swapping with what is returns from the reduce(), which could be the smallest in some cases, do you see it?

bobmwangi
Автор

I think this one would work:

public int[] sortUsingStreams(int[] unsortedArray) {
IntStream.range(0, -> IntStream.range(i, unsortedArray.length)
.reduce((left, right) -> < 0 ? left : right)
.ifPresent(smallestIndex -> {
!= i) {
tempValue = unsortedArray[i];
= unsortedArray[smallestIndex];
= tempValue;

}));
return unsortedArray;
}

bobmwangi