File tree 2 files changed +55
-0
lines changed
main/java/com/thealgorithms/sorts
test/java/com/thealgorithms/sorts
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .sorts ;
2
+
3
+ /**
4
+ * ExchangeSort is an implementation of the Exchange Sort algorithm.
5
+ *
6
+ * <p>
7
+ * Exchange sort works by comparing each element with all subsequent elements,
8
+ * swapping where needed, to ensure the correct placement of each element
9
+ * in the final sorted order. It iteratively performs this process for each
10
+ * element in the array. While it lacks the advantage of bubble sort in
11
+ * detecting sorted lists in one pass, it can be more efficient than bubble sort
12
+ * due to a constant factor (one less pass over the data to be sorted; half as
13
+ * many total comparisons) in worst-case scenarios.
14
+ * </p>
15
+ *
16
+ * <p>
17
+ * Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
18
+ * </p>
19
+ *
20
+ * @author 555vedant (Vedant Kasar)
21
+ */
22
+ class ExchangeSort implements SortAlgorithm {
23
+ /**
24
+ * Implementation of Exchange Sort Algorithm
25
+ *
26
+ * @param array the array to be sorted.
27
+ * @param <T> the type of elements in the array.
28
+ * @return the sorted array.
29
+ */
30
+ @ Override
31
+ public <T extends Comparable <T >> T [] sort (T [] array ) {
32
+ for (int i = 0 ; i < array .length - 1 ; i ++) {
33
+ for (int j = i + 1 ; j < array .length ; j ++) {
34
+ if (array [i ].compareTo (array [j ]) > 0 ) {
35
+ swap (array , i , j );
36
+ }
37
+ }
38
+ }
39
+ return array ;
40
+ }
41
+
42
+ private <T > void swap (T [] array , int i , int j ) {
43
+ T temp = array [i ];
44
+ array [i ] = array [j ];
45
+ array [j ] = temp ;
46
+ }
47
+ }
Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .sorts ;
2
+
3
+ public class ExchangeSortTest extends SortingAlgorithmTest {
4
+ @ Override
5
+ SortAlgorithm getSortAlgorithm () {
6
+ return new ExchangeSort ();
7
+ }
8
+ }
You can’t perform that action at this time.
0 commit comments