mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-14 09:22:32 +08:00
Update SelectionSort.java
-Used compareTo -Used a local swap method
This commit is contained in:

committed by
GitHub

parent
19caa9723b
commit
6818098a32
@ -8,6 +8,17 @@ package Sorts;
|
|||||||
|
|
||||||
public class SelectionSort implements SortAlgorithm {
|
public class SelectionSort implements SortAlgorithm {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method swaps the two elements in the array
|
||||||
|
* @param arr, i, j The array for the swap and
|
||||||
|
the indexes of the to-swap elements
|
||||||
|
*/
|
||||||
|
public void swap(T[] arr, int i, int j) {
|
||||||
|
T temp = arr[i];
|
||||||
|
arr[i] = arr[j];
|
||||||
|
arr[j] = temp;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method implements the Generic Selection Sort
|
* This method implements the Generic Selection Sort
|
||||||
*
|
*
|
||||||
@ -22,14 +33,14 @@ public class SelectionSort implements SortAlgorithm {
|
|||||||
int min = i;
|
int min = i;
|
||||||
|
|
||||||
for (int j = i + 1; j < n; j++) {
|
for (int j = i + 1; j < n; j++) {
|
||||||
if (SortUtils.less(arr[j], arr[min])) {
|
if (arr[min].compareTo(arr[j]) < 0) {
|
||||||
min = j;
|
min = j;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Swapping if index of min is changed
|
// Swapping if index of min is changed
|
||||||
if (min != i) {
|
if (min != i) {
|
||||||
SortUtils.swap(arr, i, min);
|
swap(arr, i, min);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user