-
Notifications
You must be signed in to change notification settings - Fork 0
/
question1.java
51 lines (43 loc) · 1.06 KB
/
question1.java
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
48
49
50
51
import java.util.Comparator;
import java.util.Random;
import java.util.Scanner;
public class question1 {
int[] array;
static boolean isPowerOfTwo (int x)
{
/* First x in the below expression is
for the case when x is 0 */
return x!=0 && ((x&(x-1)) == 0);
}
public void sort(int[] array) { // array length must be a power of 2
this.array = array;
sort(0, array.length);
}
private void sort(int low, int n) {
if (n > 1) {
int mid = n >> 1;
sort(low, mid);
sort(low + mid, mid);
combine(low, n, 1);
}
}
private void combine(int low, int n, int st) {
int m = st << 1;
if (m < n) {
combine(low, n, m);
combine(low + st, n, m);
for (int i = low + st; i + st < low + n; i += m)
compareAndSwap(i, i + st);
} else
compareAndSwap(low, low + st);
}
private void compareAndSwap(int i, int j) {
if (array[i] > array[j])
swap(i, j);
}
private void swap(int i, int j) {
int h = array[i];
array[i] = array[j];
array[j] = h;
}
}