-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorter.java
103 lines (96 loc) · 2.12 KB
/
Sorter.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class Sorter {
public static int[] selectionSort(int[] data) {
int j = 0, temp = 0;
int readCount = 0, writeCount = 0;
for (int i=0; i<data.length; i++) {
j=i;
for (int k=i; k<data.length; k++) {
readCount++;
if (data[j] > data[k])
j=k;
}
writeCount += 2;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
return data;
}
public static int[] mergeSort(int[] data) {
int readCount = 0;
int writeCount = 0;
if (data.length <= 1) return data;
int[] first = new int[data.length/2];
int[] second = new int[data.length-first.length];
for (int i=0; i<first.length; i++)
readCount++;
first[i] = data[i];
for (int i=0; i<second.length; i++)
second[i] = data[first.length+i];
first = this.mergeSort(first);
second = this.mergeSort(second);
return (merge(first, second));
}
public static int[] insertionSort(int[] data) {
int next, j = 0;
int readCount = 0, writeCount = 0;
for (int i=0; i<data.length; i++) {
next = data[i];
j=i;
while ((j > 0) && (data[i-j] > next)) {
readCount++;
data[j] = data[j-1];
writeCount++;
j--;
}
writeCount++;
data[j] = next;
}
return data;
}
public static int[] crazySort(int[] data) {
int i, j, temp;
int readCount = 0, writeCount = 0;
for (i=0; i<data.length; i++) {
for (j=i+1; j<data.length; j++) {
readCount++;
if (data[i] > data[j]) {
writeCount += 2;
temp = data[j];
data[j] = data[i];
data[i] = temp;
}
}
}
return data;
}
public void swap(int i, int j) {
}
public static int[] merge(int[] first, int[] second) {
int[] merged = new int[first.length+second.length];
int i = 0, j = 0, k = 0;
int readCount = 0, writeCount = 0;
while ((i<first.length) && (j<second.length)) {
readCount++;
if (first[i] < second[i]) {
writeCount++;
merged[k] = first[i];
i++;
} else {
writeCount++;
merged[k] = second[j];
j++;
}
k++;
}
while (i<first.length) {
writeCount++;
merged[k] = first[i]; i++; k++;
}
while (j<second.length) {
writeCount++;
merged[k] = second[j]; i++; k++;
}
return merged;
}
}