Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ShakerSort with tests #98

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/main/kotlin/sort/ShakerSort.kt
Original file line number Diff line number Diff line change
@@ -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 <T : Comparable<T>> shakerSort(arr: Array<T>) {
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)
}
28 changes: 28 additions & 0 deletions src/test/kotlin/sort/ShakerSortTest.kt
Original file line number Diff line number Diff line change
@@ -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"))
}
}