66 lines
1.6 KiB
Java
66 lines
1.6 KiB
Java
package task6;
|
|
|
|
import util.Util;
|
|
|
|
public class Sorter {
|
|
public void sort(int[] array) {
|
|
if (array == null || array.length <= 1) return;
|
|
|
|
int n = array.length;
|
|
int[] temp = new int[n];
|
|
|
|
while (true) {
|
|
int i = 0;
|
|
int merges = 0;
|
|
|
|
while (i < n) {
|
|
// Find first run
|
|
int left = i;
|
|
while (i + 1 < n && array[i] <= array[i + 1]) i++;
|
|
int mid = i;
|
|
i++;
|
|
|
|
if (i >= n) break;
|
|
|
|
// Find second run
|
|
while (i + 1 < n && array[i] <= array[i + 1]) i++;
|
|
int right = i;
|
|
i++;
|
|
|
|
// Merge both runs
|
|
merge(array, temp, left, mid, right);
|
|
merges++;
|
|
}
|
|
|
|
if (merges == 0) break;
|
|
}
|
|
}
|
|
|
|
private void merge(int[] array, int[] temp, int left, int mid, int right) {
|
|
System.arraycopy(array, left, temp, left, right - left + 1);
|
|
|
|
int i = left;
|
|
int j = mid + 1;
|
|
int k = left;
|
|
|
|
while (i <= mid && j <= right) {
|
|
if (temp[i] <= temp[j]) {
|
|
array[k++] = temp[i++];
|
|
} else {
|
|
array[k++] = temp[j++];
|
|
}
|
|
}
|
|
while (i <= mid) array[k++] = temp[i++];
|
|
while (j <= right) array[k++] = temp[j++];
|
|
}
|
|
|
|
public static final void main(String[] args) {
|
|
int[] array = new int[100000000];
|
|
Util util = new Util();
|
|
util.fillArrayRandom(array, 10000000);
|
|
Sorter mySorter = new Sorter();
|
|
mySorter.sort(array);
|
|
|
|
}
|
|
}
|