各种排序
public class Demo {
public static void main(String[] args) {
int[] a = { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
int[] b = { 1, 2, 3, 4, 5, 6, 7 };
// bubbleSort(a);
// selectSort(a);
// insertSort(a);
// shellSort(a, 10);
halfSort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
// System.out.println(halfQuery(b, 3));
}
/* 冒泡排序 */
public static void bubbleSort(int[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) {
swap(a, j, i);
}
}
}
}
/* 选择排序 */
public static void selectSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
swap(a, i, j);
}
}
}
}
/* 插入排序 */
public static void insertSort(int[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0 && a[j] < a[j - 1]; j--) {
swap(a, j, j - 1);
}
}
}
/* 希尔排序 */
public static void shellSort(int[] a, int n) {
int increment = n;
do {
if (increment % 2 == 0) {
increment = increment / 2;
} else {
increment = increment / 2 + 1;
}
shellPass(a, increment);
} while (increment > 1);
}
public static void shellPass(int[] a, int d) {
for (int i = 0; i < a.length - d; i++) {
if (a[i] > a[i + d]) {
swap(a, i, i + d);
}
}
}
public static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
/* 二分法查找 */
public static int halfQuery(int[] a, int key) {
int low = 0, high = a.length - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > key) {
high = mid - 1;
} else if (a[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
/* 二分法排序 */
public static void halfSort(int[] a) {
int low, high, mid;
int temp;
for (int i = 1; i < a.length; i++) {
temp = a[i];
low = 0;
high = i - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > a[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
for (int j = i - 1; j > high; j--) {
a[j + 1] = a[j];
}
a[high + 1] = temp;
}
}
}