几种常见的排序算法
冒泡排序-不推荐使用,面试最好不写,性能最慢
/**
* 冒泡排序,速度最慢,一般是不会考察
*/
public class 冒泡排序 {
public static int[] moBaoPaiXu(int[] array) {
// 外面一层训话控制循环次数
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]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
public static void main(String[] args) {
int[] array = new int[]{10,2,1,80,6,18,9,60,3};
int[] ints = moBaoPaiXu(array);
System.out.println(Arrays.toString(ints));
}
}
快速排序的流程图
总流程图
public class 快速排序 {
/**
* 选base = left,定义左右指针,low,high
*/
public static void quickSort(int[] array,int left,int right) {
// 因为是递归,所以必须加递归结束条件,否则出现死循环,数组越界
if(array == null || array.length < 1 || left >= right) {
return;
}
int low = left;
int high = right;
int base = array[left];
while (low != high) {
// high从右边向左边检索,找到了比base小的停下来,
while (low < high && array[high] >= base) {
high--;
}
// low从左向右检索,找到了比base大的停下来,
while (low < high && array[low] <= base) {
low++;
}
// 位置交换,继续检索,
int temp = array[low];
array[low] = array[high];
array[high] = temp;
}
// 直到low = high,交换low和base的位置
array[left] = array[low];
array[low] = base;
// 之后递归,先检索左边区间的,在加索右边区间的,按照上面步骤(先从右边high指针检索,在从左边检索)
quickSort(array,left,low - 1);
quickSort(array,low + 1,right);
}
归并排序-常考
public class 归并排序 {
private static void chaifen(int[] array, int low, int high) {
if (low >= high) {
return;
}
int mid = (low + high) / 2;
chaifen(array, low, mid);
chaifen(array, mid + 1, high);
merger(array, low, mid, high);
}
/**
* 将片段进行合并
*/
private static void merger(int[] array, int low, int mid, int high) {
int i = low;
int j = mid + 1;
int[] temp = new int[high - low + 1];
int index = 0;
while (i <= mid && j <= high) {
if (array[i] < array[j]) {
temp[index] = array[i];
i++;
} else {
// 存在有序对,
temp[index] = array[j];
j++;
}
index++;
}
while (i <= mid) {
temp[index] = array[i];
i++;
index++;
}
while (j <= high) {
temp[index] = array[j];
j++;
index++;
}
for (int h = 0; h < temp.length; h++) {
array[low + h] = temp[h];
}
}
public static void main(String[] args) {
int[] a = {10, 8, 5, 60, 9, 2, 6, 3};
chaifen(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
}
归并,快排必须掌握,且灵活运用