public void shellSort(int[] array) {
int gap = array.length;
while (gap > 0) {
gap = gap / 2;
shell(array, gap);
}
}
public void shell(int[] array, int gap) {
for (int i = gap; i < array.length; i++) {
int tmp = array[i];
int j = i - gap;
for (; j >= 0; j--) {
if (array[j] > tmp) {
array[j + gap] = array[j];
} else {
break;
}
}
array[j + gap] = tmp;
}
}
public void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
swap(array, i, minIndex);
}
}
public void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public void mergeSort(int[] array) {
branch(array, 0, array.length - 1);
}
public void branch(int[] array, int left, int right) {
if (left >= right) {
return;
}
int mid = left + ((right - left) >> 1);
branch(array, left, mid);// 分解左子序列
branch(array, mid + 1, right);// 分解右子序列
merge(array, left, mid, right); // 合并子序列
}
public void merge(int[] array, int left, int mid, int right) {
int s1 = left;
int e1 = mid;
int s2 = mid + 1;
int e2 = right;
int index = 0;
int[] ans = new int[right - left + 1];
while (s1 <= e1 && s2 <= e2) {
if (array[s1] <= array[s2]) {
ans[index++] = array[s1++];
} else {
ans[index++] = array[s2++];
}
}
while (s1 <= e1) {
ans[index++] = array[s1++];
}
while (s2 <= e2) {
ans[index++] = array[s2++];
}
for (int i = left; i <= right; i++) {
array[i] = ans[i - left];
}
}
2.归并排序--非递归
java复制代码
public void merge(int[] array, int left, int mid, int right) {
int s1 = left;
int e1 = mid;
int s2 = mid + 1;
int e2 = right;
int index = 0;
int[] ans = new int[right - left + 1];
while (s1 <= e1 && s2 <= e2) {
if (array[s1] <= array[s2]) {
ans[index++] = array[s1++];
} else {
ans[index++] = array[s2++];
}
}
while (s1 <= e1) {
ans[index++] = array[s1++];
}
while (s2 <= e2) {
ans[index++] = array[s2++];
}
for (int i = left; i <= right; i++) {
array[i] = ans[i - left];
}
}
public void mergeSortNor(int[] array) {
int gap = 1;
while (gap < array.length) {
for (int i = 0; i < array.length; i++) {
int left = i;
int mid = left + gap - 1;
if (mid >= array.length) {
mid = array.length - 1;
}
int right = mid + gap;
if (right >= array.length) {
right = array.length - 1;
}
merge(array, left, mid, right);
}
gap *= 2;
}
}