Skip to content

Commit 3725759

Browse files
author
evitwilly
committed
added a new sorting algorithm Tim sort, added comments for MergeSort.kt file, edited some old comments
1 parent 9fb4597 commit 3725759

File tree

13 files changed

+204
-32
lines changed

13 files changed

+204
-32
lines changed
Binary file not shown.
Binary file not shown.

.gradle/7.1/fileHashes/fileHashes.bin

300 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
Binary file not shown.

.idea/gradle.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/main/kotlin/main.kt

Lines changed: 0 additions & 7 deletions
This file was deleted.

src/main/kotlin/sorting/MergeSort.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
package sorting
22

3+
/**
4+
* merge sort algorithm implemented without recursion
5+
*
6+
* the best time: n * log(n)
7+
* average time: n * log(n)
8+
* worst time: n * log(n)
9+
*
10+
* amount of memory: n
11+
*
12+
*/
13+
314
fun <T : Comparable<T>> Array<T>.mergeSort() {
415
val temporaryArray = this.copyOf()
516

src/main/kotlin/sorting/MergeSortRecursive.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
package sorting
22

33
/**
4-
* merge sort algorithm
4+
* merge sort algorithm implemented with recursion
55
*
6-
* worst time: n * log(n)
76
* the best time: n * log(n)
87
* average time: n * log(n)
8+
* worst time: n * log(n)
99
*
1010
* amount of memory: n
11+
*
1112
*/
1213

1314
fun Array<Int>.mergeSortRecursive() {

src/main/kotlin/sorting/TimSort.kt

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package sorting
2+
3+
import java.lang.Integer.min
4+
5+
/**
6+
* Tim sort algorithm
7+
*
8+
* the best time: n
9+
* average time: n * log(n)
10+
* worst time: n * log(n)
11+
*
12+
* amount of memory: n
13+
*
14+
*/
15+
16+
fun Array<Int>.timSort() {
17+
val size = size
18+
val minrun = minrun(size)
19+
var index = 0
20+
while (index < size) {
21+
insertionSort(this, index, min(index + minrun - 1, size - 1))
22+
index += minrun
23+
}
24+
25+
var mergingSize = minrun
26+
while (mergingSize < size) {
27+
28+
var left = 0
29+
while (left < size) {
30+
val middle = left + mergingSize - 1
31+
val right = min(left + 2 * mergingSize - 1, size - 1)
32+
if (middle < right) {
33+
merge(this, left, middle, right)
34+
}
35+
left += mergingSize * 2
36+
}
37+
38+
mergingSize *= 2
39+
}
40+
}
41+
42+
private fun minrun(n: Int) : Int {
43+
var addedValue = 0
44+
var size = n
45+
if (size >= 64) {
46+
addedValue = addedValue or (size and 1)
47+
size = size.shr(1)
48+
}
49+
return size + addedValue
50+
}
51+
52+
private fun insertionSort(array: Array<Int>, left: Int, right: Int) {
53+
var outerIndex = left + 1
54+
while (outerIndex <= right) {
55+
val temporaryValue = array[outerIndex]
56+
var innerIndex = outerIndex - 1
57+
while (innerIndex >= left && array[innerIndex] > temporaryValue) {
58+
array[innerIndex + 1] = array[innerIndex]
59+
innerIndex--
60+
}
61+
array[innerIndex + 1] = temporaryValue
62+
outerIndex++
63+
}
64+
}
65+
66+
private fun merge(array: Array<Int>, left: Int, middle: Int, right: Int) {
67+
val leftLengthArray = middle - left + 1
68+
val rightLengthArray = right - middle
69+
70+
var index = 0
71+
var leftArray = Array(leftLengthArray) { 0 }
72+
while (index < leftLengthArray) {
73+
leftArray[index] = array[left + index]
74+
index++
75+
}
76+
77+
index = 0
78+
var rightArray = Array(rightLengthArray) { 0 }
79+
while (index < rightLengthArray) {
80+
rightArray[index] = array[middle + 1 + index]
81+
index++
82+
}
83+
84+
var leftArrayIndex = 0
85+
var rightArrayIndex = 0
86+
index = 0
87+
88+
while (leftArrayIndex < leftLengthArray && rightArrayIndex < rightLengthArray) {
89+
if (leftArray[leftArrayIndex] <= rightArray[rightArrayIndex]) {
90+
array[index] = leftArray[leftArrayIndex]
91+
leftArrayIndex++
92+
} else {
93+
array[index] = rightArray[rightArrayIndex]
94+
rightArrayIndex++
95+
}
96+
index++
97+
}
98+
99+
while (leftArrayIndex < leftLengthArray) {
100+
array[index] = leftArray[leftArrayIndex]
101+
leftArrayIndex++
102+
index++
103+
}
104+
105+
while (rightArrayIndex < rightLengthArray) {
106+
array[index] = rightArray[rightArrayIndex]
107+
rightArrayIndex++
108+
index++
109+
}
110+
}

src/main/kotlin/structures/DynamicArray.kt

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,25 @@ package structures
33
import java.lang.IllegalStateException
44

55
/**
6-
* структура данных: динамический массив
6+
* data structure: dynamic array
77
*
8-
* описание: обертка над обычным массивом, в которой осуществляется проверка индексов
9-
* и при переполнении массива, его размер увеличивается динамически
8+
* description: wrapper over a regular array, in which indexes are checked and
9+
* when the array overflows, its size increases dynamically
10+
*
11+
* @constructor
12+
* @param capacity initial array size
1013
*/
1114

1215
class DynamicArray(private var capacity: Int = 10) {
1316
private var data = Array(capacity) { 0 }
1417
private var index = 0
1518

1619
/**
17-
* добавляет новый элемент в массив
20+
* add a new element in array
1821
*
19-
* если массив не может вместить новый элемент, то его размер динамически увеличивается
22+
* if the array cannot accommodate the new element, then its size is dynamically increased
2023
*
21-
* @value - элемент
24+
* @param value - element
2225
*/
2326
fun add(value: Int) {
2427
if (index < data.size - 1) {
@@ -30,9 +33,9 @@ class DynamicArray(private var capacity: Int = 10) {
3033
}
3134

3235
/**
33-
* удаляет элемент из массива и сдвигает на его место последующие
36+
* removes an element from the array and shifts subsequent elements in its place
3437
*
35-
* @value - элемент
38+
* @param value - element
3639
*/
3740
fun remove(value: Int) : Boolean {
3841
val foundedIndex = data.indexOf(value)
@@ -46,21 +49,21 @@ class DynamicArray(private var capacity: Int = 10) {
4649
}
4750

4851
/**
49-
* проверяет на существование элемента в массиве
52+
* checks for the existence of an element in an array
5053
*
51-
* @value - элемент
54+
* @param value - element
5255
*
53-
* @return возвращает true, если элемент присутствует в массиве
56+
* @return returns true if the element is present in the array
5457
*/
5558
fun contains(value: Int) = data.contains(value)
5659

5760
/**
58-
* устанавливает новое значения элемента для указанного индекса
61+
* sets the new element value at the specified index
5962
*
60-
* @index - индекс элемента
61-
* @value - новое значение элемента
63+
* @param index - element index
64+
* @param value - the new value of the element
6265
*
63-
* @return возвращает true, если элемент был успешно изменен
66+
* @return returns true if the element was successfully modified
6467
*/
6568
fun set(index: Int, value: Int) : Boolean {
6669
if (isBound(index)) {
@@ -72,11 +75,11 @@ class DynamicArray(private var capacity: Int = 10) {
7275

7376

7477
/**
75-
* возвращает значение элемента по индексу или генерирует исключение, если некорректный индекс
78+
* returns the value of the element by index, or throws an exception if the index is invalid
7679
*
77-
* @index - индекс элемента
80+
* @param index - element index
7881
*
79-
* @return возвращает значение элемента по индексу
82+
* @return returns the value of an element by index
8083
*/
8184
fun get(index: Int) : Int {
8285
if (isBound(index)) {
@@ -87,23 +90,23 @@ class DynamicArray(private var capacity: Int = 10) {
8790
}
8891

8992
/**
90-
* возвращает размер массива
93+
* returns the size of the array
9194
*
92-
* @return возвращает размер массива
9395
*/
9496
fun capacity() = capacity
9597

9698
/**
97-
* проверка на корретный индекс
99+
* check for correct index
98100
*
99-
* @return возвращает true, если индекс входит в диапазон доступных индексов
101+
* @return returns true if the index is within the range of available indexes
100102
*/
101103
private fun isBound(i: Int) = i in 0 until index
102104

103105
override fun toString() = data.joinToString(", ")
104106

105107
/**
106-
* увеличивает размер массива, когда его нехватает
108+
* increases the size of an array when there is not enough to add new elements
109+
*
107110
*/
108111
private fun increaseSize() {
109112
capacity *= 2

src/main/kotlin/structures/Graph.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ import java.util.LinkedList
66
* data structure: graph
77
*
88
* description: a graph is made up of vertices connected by edges
9+
*
910
*/
1011

1112
class Graph<T> {
13+
1214
private val data = mutableMapOf<Vertex<T>, MutableList<Vertex<T>>>()
1315

1416
/**
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package sorting
2+
3+
import org.junit.Test
4+
import org.junit.jupiter.api.Assertions
5+
6+
class TimSortTest {
7+
8+
@Test
9+
fun test_reversed_array() {
10+
val expected = TestUtils.list(100000)
11+
12+
val actual = expected.reversed().toTypedArray()
13+
actual.timSort()
14+
15+
Assertions.assertEquals(expected, actual.toList())
16+
}
17+
18+
@Test
19+
fun test_random_array() {
20+
val actual = TestUtils.randomArray(50000)
21+
22+
val expected = actual.sorted()
23+
24+
actual.timSort()
25+
26+
Assertions.assertEquals(expected, actual.toList())
27+
}
28+
29+
@Test
30+
fun test_shuffled_array() {
31+
val expected = TestUtils.sortedArray(100000)
32+
33+
val actual = expected.copyOf()
34+
actual.shuffle()
35+
actual.timSort()
36+
37+
Assertions.assertEquals(expected.toList(), actual.toList())
38+
}
39+
40+
@Test
41+
fun test_sorted_array() {
42+
val actual = TestUtils.sortedArray(100000)
43+
44+
val expected = actual.toList()
45+
46+
actual.timSort()
47+
48+
Assertions.assertEquals(expected, actual.toList())
49+
}
50+
51+
}

0 commit comments

Comments
 (0)