1、插入排序
public static int[] insertSort(int[] array) {
int length = array.length;
int j = 0;
for(int i = 1; i < length; i++) {
int temp = array[i];
for(j = i; j > 0; j--) {
if(temp < array[j-1]) {
array[j] = array[j-1];
}else {
break;
}
}
array[j] = temp;
}
return array;
}
2、冒泡排序
public static int[] bubbleSort(int[] array) {
int length = array.length;
for(int i = 0; i < length; i++ ) {
for(int j = 1; j < length - i; j++) {
if(array[j] < array[j -1]) {
int temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
return array;
}
3、快速排序
public static void quickSort2(int[] a,int low,int high) {
if(low >= high) {
return ;
}
int i = low;
int j = high;
int temp = a[low];
while(i < j) {
//先从右边开始,找到第一个比temp小的数,注意是a[j] >= temp
while(i < j && a[j] >= temp) j--;
while(i < j && a[i] <= temp) i++;
if(i < j) {
//交换位置
int temp1 = a[i];
a[i] = a[j];
a[j] = temp1;
}
}
//基准数归位
a[low] = a[i];
a[i] = temp;
quickSort2(a,low,i-1);
quickSort2(a,j+1,high);
}
4、堆排序
https://www.cnblogs.com/chengxiao/p/6129630.html
- 堆是一个完全二叉树的结构,分为大顶堆和小顶堆。大顶堆即是节点的值大于左右节点的值。
- 堆排序的思路是:
a.将无需序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆;
b.将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端;
c.重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到整个序列有序。
网友评论