From 14b3f45f9f32df108de5d0eace624f23d6bbe1bf Mon Sep 17 00:00:00 2001 From: VedantK <145242784+555vedant@users.noreply.github.com> Date: Thu, 1 Feb 2024 13:55:31 +0530 Subject: [PATCH] Add `ExchangeSort` (#5029) * added ExchangeSort and its testcases --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> --- .../com/thealgorithms/sorts/ExchangeSort.java | 47 +++++++++++++++++++ .../thealgorithms/sorts/ExchangeSortTest.java | 8 ++++ 2 files changed, 55 insertions(+) create mode 100644 src/main/java/com/thealgorithms/sorts/ExchangeSort.java create mode 100644 src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java diff --git a/src/main/java/com/thealgorithms/sorts/ExchangeSort.java b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java new file mode 100644 index 00000000..28303430 --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java @@ -0,0 +1,47 @@ +package com.thealgorithms.sorts; + +/** + * ExchangeSort is an implementation of the Exchange Sort algorithm. + * + *

+ * Exchange sort works by comparing each element with all subsequent elements, + * swapping where needed, to ensure the correct placement of each element + * in the final sorted order. It iteratively performs this process for each + * element in the array. While it lacks the advantage of bubble sort in + * detecting sorted lists in one pass, it can be more efficient than bubble sort + * due to a constant factor (one less pass over the data to be sorted; half as + * many total comparisons) in worst-case scenarios. + *

+ * + *

+ * Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort + *

+ * + * @author 555vedant (Vedant Kasar) + */ +class ExchangeSort implements SortAlgorithm { + /** + * Implementation of Exchange Sort Algorithm + * + * @param array the array to be sorted. + * @param the type of elements in the array. + * @return the sorted array. + */ + @Override + public > T[] sort(T[] array) { + for (int i = 0; i < array.length - 1; i++) { + for (int j = i + 1; j < array.length; j++) { + if (array[i].compareTo(array[j]) > 0) { + swap(array, i, j); + } + } + } + return array; + } + + private void swap(T[] array, int i, int j) { + T temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} diff --git a/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java b/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java new file mode 100644 index 00000000..6c4271fa --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java @@ -0,0 +1,8 @@ +package com.thealgorithms.sorts; + +public class ExchangeSortTest extends SortingAlgorithmTest { + @Override + SortAlgorithm getSortAlgorithm() { + return new ExchangeSort(); + } +}