Skip to content

Commit 35f21f3

Browse files
committed
Refactored SelectionSort
1 parent 3c40937 commit 35f21f3

File tree

1 file changed

+21
-34
lines changed

1 file changed

+21
-34
lines changed

Sorts/SelectionSort.java

+21-34
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,60 @@
1+
package Sorts;
2+
3+
import static Sorts.SortUtils.*;
4+
15
/**
26
*
37
* @author Varun Upadhyay (https://github.com/varunu28)
48
*
59
*/
610

7-
public class SelectionSort {
11+
public class SelectionSort implements SortAlgorithm {
812

913
/**
1014
* This method implements the Generic Selection Sort
1115
*
1216
* @param arr The array to be sorted
13-
* @param n The count of total number of elements in array
1417
* Sorts the array in increasing order
1518
**/
16-
17-
public static <T extends Comparable<T>> void SS(T[] arr, int n) {
18-
19-
for (int i=0;i<n-1;i++) {
20-
19+
@Override
20+
public <T extends Comparable<T>> T[] sort(T[] arr) {
21+
int n = arr.length;
22+
for (int i = 0; i < n - 1; i++) {
2123
// Initial index of min
2224
int min = i;
2325

24-
for (int j=i+1;j<n;j++) {
25-
if (arr[j].compareTo(arr[min]) < 0) {
26+
for (int j = i +1 ; j < n; j++) {
27+
if (less(arr[j], arr[min])) {
2628
min = j;
2729
}
2830
}
2931

3032
// Swapping if index of min is changed
3133
if (min != i) {
32-
T temp = arr[i];
33-
arr[i] = arr[min];
34-
arr[min] = temp;
34+
swap(arr, i , min);
3535
}
3636
}
37+
38+
return arr;
3739
}
3840

3941
// Driver Program
4042
public static void main(String[] args) {
4143

42-
// Integer Input
43-
int[] arr1 = {4,23,6,78,1,54,231,9,12};
44-
int n = arr1.length;
44+
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
4545

46-
Integer[] array = new Integer[n];
47-
for (int i=0;i<n;i++) {
48-
array[i] = arr1[i];
49-
}
46+
SelectionSort selectionSort = new SelectionSort();
5047

51-
SS(array, n);
48+
Integer[] sorted = selectionSort.sort(arr);
5249

5350
// Output => 1 4 6 9 12 23 54 78 231
54-
for(int i=0; i<n; i++)
55-
{
56-
System.out.print(array[i]+"\t");
57-
}
58-
59-
System.out.println();
51+
print(sorted);
6052

6153
// String Input
62-
String[] array1 = {"c", "a", "e", "b","d"};
63-
n = array1.length;
64-
65-
SS(array1, n);
54+
String[] strings = {"c", "a", "e", "b","d"};
55+
String[] sortedStrings = selectionSort.sort(strings);
6656

6757
//Output => a b c d e
68-
for(int i=0; i<n; i++)
69-
{
70-
System.out.print(array1[i]+"\t");
71-
}
58+
print(sortedStrings);
7259
}
7360
}

0 commit comments

Comments
 (0)