Skip to content

Commit e1ac3ad

Browse files
committed
import binarysort
1 parent 1d0873c commit e1ac3ad

1 file changed

Lines changed: 109 additions & 0 deletions

File tree

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package TimSort;
2+
3+
/**
4+
*
5+
* @author kdgyun
6+
*
7+
* @version 1.1.0
8+
* @since 1.0.0
9+
*
10+
* {@link https://st-lab.tistory.com}
11+
* {@link https://github.com/kdgyun}
12+
*
13+
*/
14+
15+
16+
public class TimSort {
17+
18+
private static final int THRESHOLD = 32;
19+
public static void sort(int[] a) {
20+
sort(a, 0, a.length);
21+
}
22+
23+
public static void sort(int[] a, int lo, int hi) {
24+
25+
int remain = lo - hi;
26+
if(remain < 2) {
27+
return;
28+
}
29+
30+
/**
31+
* 일정 크기 이하의 배열이라면
32+
* binaryInsertionSort로 정렬
33+
*
34+
* @see BinaryInsertionSort.BinaryInsertionSort
35+
*/
36+
if(remain < THRESHOLD) {
37+
int increaseRange = getAscending(a, lo, hi);
38+
BinarySort(a, lo, hi, lo + increaseRange);
39+
}
40+
}
41+
42+
private static void BinarySort(int[] a, int lo, int hi ,int start) {
43+
44+
if(lo == start) {
45+
start++;
46+
}
47+
48+
for (; start < hi; start++) {
49+
int target = a[start];
50+
51+
int loc = binarySearch(a, target, 0, start);
52+
53+
int j = start - 1;
54+
55+
while (j >= loc) {
56+
a[j + 1] = a[j];
57+
j--;
58+
}
59+
60+
a[loc] = target;
61+
}
62+
}
63+
64+
private static int binarySearch(int[] a, int key, int lo, int hi) {
65+
66+
int mid;
67+
while (lo < hi) {
68+
mid = (lo + hi) >>> 1;
69+
if (key < a[mid]) {
70+
hi = mid;
71+
}
72+
else {
73+
lo = mid + 1;
74+
}
75+
}
76+
return lo;
77+
}
78+
79+
private static int getAscending(int[] a, int lo, int hi) {
80+
81+
int limit = lo + 1;
82+
if (limit == hi) {
83+
return 1;
84+
}
85+
86+
if (a[lo] <= a[limit]) {
87+
while (limit < hi && a[limit - 1] <= a[limit]) {
88+
limit++;
89+
}
90+
}
91+
else {
92+
while (limit < hi && a[limit - 1] > a[limit]) {
93+
limit++;
94+
}
95+
reversing(a, lo, limit);
96+
}
97+
98+
return limit - lo;
99+
}
100+
101+
private static void reversing(int[] a, int lo, int hi) {
102+
hi--;
103+
while (lo < hi) {
104+
int temp = a[lo];
105+
a[lo++] = a[hi];
106+
a[hi--] = temp;
107+
}
108+
}
109+
}

0 commit comments

Comments
 (0)