Skip to content

Commit 14b3f45

Browse files
555vedantvil02
andauthored
Add ExchangeSort (TheAlgorithms#5029)
* added ExchangeSort and its testcases --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
1 parent b99aeef commit 14b3f45

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class ExchangeSortTest extends SortingAlgorithmTest {
4+
@Override
5+
SortAlgorithm getSortAlgorithm() {
6+
return new ExchangeSort();
7+
}
8+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy