1.bubbleSort冒泡排序模板
public static void bubbleSort(int[] array) {
boolean flag = false;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = true;
}
}
if (!flag) {
break;
} else {
flag = false;
}
}
}
2.selectSort简单选择排序模板
public static void selectSort(int[] array) {
if (array == null || array.length < 2) {
return;
}
for (int i = 0; i < array.length - 1; i++) {
int index = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[index]) {
index = j;
}
}
if (index != i) {
int temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
}
3.insertSort直接插入排序模板
public static void insertSort(int[] array) {
if (array == null || array.length < 2) {
return;
}
for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
} else {
break;
}
}
}
}
4.quickSort快速排序模板
public static void quickSort(int[] array, int low, int height) {
if (low >= height) {
return;
}
int sum = array[low];
int left = low;
int right = height;
while (left != right) {
while (array[right] >= sum && right > left)
right--;
while (array[left] <= sum && right > left)
left++;
if (right > left) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
array[low] = array[left];
array[left] = sum;
quickSort(array, low, left - 1);
quickSort(array, left + 1, height);
}
注:调用方法要注意下标。如下例:
quickSort(array, 0, array.length-1);



