-
冒泡排序
简单的冒泡排序我就不赘述了,这里提供给大家的是改进冒泡排序法。
public void sort(int[] data) {
int low = 0;
int high = data.length - 1;
int index = low;
while (high > low) {
for (int i = low; i < high; i++) {
if (data[i] > data[i + 1]) {
Calculator.Swap(data, i, i + 1);
index = i;
}
}
high = index;
for (int i = high; i > low; i--) {
if (data[i] < data[i - 1]) {
Calculator.Swap(data, i, i - 1);
index = i;
}
}
low = index;
}
} -
插入排序
public void sort(int[] data) {
for (int i = 1; i < data.length; i++) {
int temp = data[i];
int j = i - 1;
while (temp < data[j]) {
data[j + 1] = data[j];
j--;
if (j == -1) {
break;
}
}
data[j + 1] = temp;
}
} -
选择排序
public void sort(int[] data) {
for (int i = 0; i < data.length; i++) {
int index = i;
for (int j = i + 1; j < data.length; j++) {
if (data[j] < data[index]) {
index = j;
}
}
if (i != index) {
Calculator.Swap(data, i, index);
}
}
} -
希尔排序
public void sort(int[] data, int index) {
int j;
int temp;
int dataLength;
int pointer;
dataLength = (int) index / 2;
while (dataLength != 0) {
for (j = dataLength; j < index; j++) {
temp = data[j];
pointer = j - dataLength;
while (temp < data[pointer] && pointer >= 0 && pointer <= index) {
data[pointer + dataLength] = data[pointer];
pointer = pointer - dataLength;
if (pointer < 0 || pointer > index)
break;
}
data[pointer + dataLength] = temp;
}
dataLength = dataLength / 2;
}
} -
归并排序
public void merge(int[] a, int low, int mid, int high) {
int[] b = new int[high - low + 1];
int s = low;
int t = mid + 1;
int k = 0;
while (s <= mid && t <= high) {
if (a[s] <= a[t])
b[k++] = a[s++];
else
b[k++] = a[t++];
}
while (s <= mid)
b[k++] = a[s++];
while (t <= high)
b[k++] = a[t++];
for (int i = 0; i < b.length; i++) {
a[low + i] = b[i];
}
}
public void mergesort(int a[], int low, int high) {
if (low < high) {
mergesort(a, low, (low + high) / 2);
mergesort(a, (low + high) / 2 + 1, high);
merge(a, low, (high + low) / 2, high);
}
}
public void sort(int[] data) {
mergesort(data, 0, data.length - 1);
} -
快速排序
public void sort(int[] data, int left, int right) {
if (left < right) {
int index = data[left];
int i = left;
int j = right + 1;
while (true) {
while (i + 1 < data.length && data[++i] < index)
;
while (j - 1 > -1 && data[--j] > index)
;
if (i >= j) {
break;
} else {
Calculator.Swap(data, i, j);
}
}
data[left] = data[j];
data[j] = index;
sort(data, left, j - 1);
sort(data, j + 1, right);
}
}