-
Notifications
You must be signed in to change notification settings - Fork 109
/
SwapAlgorithm.kt
47 lines (40 loc) · 1.54 KB
/
SwapAlgorithm.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package other
/**
*
* Algorithm for exchanging two variables without a third additional
*
*/
class SwapAlgorithm {
// swaps two list values at the specified indexes
fun swap(list: MutableList<Int>, oldIndex: Int, newIndex: Int) {
if (oldIndex in list.indices && newIndex in list.indices) {
list[oldIndex] = list[oldIndex] + list[newIndex]
list[newIndex] = list[oldIndex] - list[newIndex]
list[oldIndex] = list[oldIndex] - list[newIndex]
}
}
// swaps two array values at the specified indexes
fun swap(array: Array<Int>, oldIndex: Int, newIndex: Int) {
if (oldIndex in array.indices && newIndex in array.indices) {
array[oldIndex] = array[oldIndex] + array[newIndex]
array[newIndex] = array[oldIndex] - array[newIndex]
array[oldIndex] = array[oldIndex] - array[newIndex]
}
}
// swaps two list values using Kotlin language features
fun swapKotlin(list: MutableList<Int>, oldIndex: Int, newIndex: Int) {
if (oldIndex in list.indices && newIndex in list.indices) {
list[oldIndex] = list[newIndex].apply {
list[newIndex] = list[oldIndex]
}
}
}
// swaps two array values using Kotlin language features
fun swapKotlin(array: Array<Int>, oldIndex: Int, newIndex: Int) {
if (oldIndex in array.indices && newIndex in array.indices) {
array[oldIndex] = array[newIndex].apply {
array[newIndex] = array[oldIndex]
}
}
}
}