一,直接插入排序
基本思想:将一个记录插入到已排序好的有序表中,从而得到一个新记录数增1的有序表。即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
要点:设立哨兵,作为临时存储和判断数组边界。
直接插入排序示例:
如果碰见一个和插入元素相等的,那么插入元素把想插入的元素放在相等元素的后面。所以,相等元素的前后顺序没有改变,从原无序序列出去的顺序就是排好序后的顺序,所以插入排序是稳定的。
算法实现:
public static void main(String[] args) {
//插入排序:直接插入排序
int[] array = {49,38,65,97,76,13,27,49};
InsertSort(array);
}
public static void InsertSort(int[] a){
for (int i = 1; i < a.length; i++) {
int x = a[i]; //复制为哨兵,存储待排序元素
int j;
for(j = i - 1;j >= 0 && a[j] > x;j--){
a[j+1] = a[j];
}
a[j+1] = x;
}
System.out.println(Arrays.toString(a));
}
输出结果:[13, 27, 38, 49, 49, 65, 76, 97]
二,希尔排序
希尔排序又叫缩小增量排序
基本思想:先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。
算法实现:
public static final int[] ARRAY = {12, 9, 6, 11, 5, 1, 14, 2, 10, 4, 8, 7, 13, 3};
public static int[] sort(int[] array) {
int len = array.length;
if (len < 2) {
return array;
}
//当前待排序数据,该数据之前的已被排序
int current;
//增量
int gap = len / 2;
while (gap > 0) {
for (int i = gap; i < len; i++) {
current = array[i];
//前面有序序列的索引
int index = i - gap;
while (index >= 0 && current < array[index]) {
array[index + gap] = array[index];
//有序序列的下一个
index -= gap;
}
//插入
array[index + gap] = current;
}
//int相除取整
gap = gap / 2;
}
return array;
}
public static void print(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println("");
}
public static void main(String[] args) {
print(ARRAY);
System.out.println("============================================");
print(sort(ARRAY));
}
输出结果:
12 9 6 11 5 1 14 2 10 4 8 7 13 3
============================================
1 2 3 4 5 6 7 8 9 10 11 12 13 14
三,简单选择排序
基本思想:在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
算法实现:
public static void main(String[] args) {
//选择排序
int[] array = {49,38,65,97,76,13,27,10};
SelectSort(array);
}
public static void SelectSort(int[] a){
for (int i = 0; i < a.length; i++) {
//初始化一个变量,用来记录最小数字的下标
// 初始默认假设第一个数字就是最小数字
int minIndex = i;
for (int j = i+1; j < a.length ; j++) {
//如果找到更小的数字
if (a[minIndex] > a[j]) {
//将minIndex变量的值修改为新的最小数字的下标
minIndex = j;
}
}
//将最小的数字替换到第一个位置
// 将第一个位置的数字放到最小数字原来的位置
int temp=a[i];
a[i]=a[minIndex];
a[minIndex]=temp;
}
System.out.println(Arrays.toString(a));
}
输出结果:[10, 13, 27, 38, 49, 65, 76, 97]
四,冒泡排序
基本思想:相邻两个元组比较,交换
算法实现:
public static void main(String[] args) {
int[] array = {6,1,7,5,4,10,2};
Bubble_sort(array);
}
//冒泡排序
public static void Bubble_sort(int[] a){
int temp = 0;
//外层循环,判断走多少次
for (int i = 0; i < a.length-1; i++) {
//内层循环,比较相邻两个数
for (int j = 0; j < a.length-1; j++) {
if(a[j+1] < a[j]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(a));
}
输出结果:
[1, 2, 4, 5, 6, 7, 10]