diff --git a/src/main/kotlin/sort/ShakerSort.kt b/src/main/kotlin/sort/ShakerSort.kt new file mode 100644 index 0000000..d6f8791 --- /dev/null +++ b/src/main/kotlin/sort/ShakerSort.kt @@ -0,0 +1,49 @@ +package sort + +/** + * This function implements the Shaker Sort. + * + * @param array The array to be sorted + * Sorts the array in increasing order + * + * Worst-case performance O(n2) + * Best-case performance O(n) + * Average-case performance O(n2) + * Worst-case space complexity O(n2) + */ +fun > shakerSort(arr: Array) { + var left = 0 + var right = arr.lastIndex + var swapped: Boolean + + do { + swapped = false + + for (i in left until right) { + if (arr[i] > arr[i + 1]) { + val temp = arr[i] + arr[i] = arr[i + 1] + arr[i + 1] = temp + swapped = true + } + } + + if (!swapped) { + break + } + + swapped = false + right-- + + for (i in right downTo left) { + if (arr[i] > arr[i + 1]) { + val temp = arr[i] + arr[i] = arr[i + 1] + arr[i + 1] = temp + swapped = true + } + } + + left++ + } while (swapped) +} diff --git a/src/test/kotlin/sort/ShakerSortTest.kt b/src/test/kotlin/sort/ShakerSortTest.kt new file mode 100644 index 0000000..26d0003 --- /dev/null +++ b/src/test/kotlin/sort/ShakerSortTest.kt @@ -0,0 +1,28 @@ +package sort + +import org.junit.Assert.assertArrayEquals +import org.junit.Test + +class ShakerSortTest { + + @Test + fun testShakeSort() { + val array = arrayOf(4,3,2,8,1) + shakerSort(array) + assertArrayEquals(array, arrayOf(1,2,3,4,8)) + } + + @Test + fun testShakeSort2() { + val array = arrayOf(20, 5, 16, -1, 6) + shakerSort(array) + assertArrayEquals(array, arrayOf(-1, 5, 6, 16, 20)) + } + + @Test + fun testShakeSort3() { + val array = arrayOf("A", "D", "E", "C", "B") + shakerSort(array) + assertArrayEquals(array, arrayOf("A", "B", "C", "D", "E")) + } +}