插入排序
1、直接插入排序
最简单粗暴的方法,基本操作是将一个未排序的元素插入到已经排好序的元素中,从而得到一个新的、元素加1的有序数组。
- 直接上代码
public static void InsertSort(int nums[]) {
//要比较的轮数
for(int i = 1; i < nums.length; i++) {
int temp = nums[i]; //作为每次需要插入的数
int j = 0;
for(j = i - 1; j >= 0; j--) {
if(nums[j] > temp) {
nums[j + 1] = nums[j];
} else {
break;
}
}
nums[j + 1] = temp;
}
}
- 测试结果
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 6, 5 };
InsertSort(arr);
for(int i : arr) {
System.out.println(i);
}
}
2、折半插入排序
折半插入排序是在直接插入排序的基础上,每次插入过程使用二分查找法进行排序。
- 代码实现
public static void binaryInsertSort(int[] a) {
int n = a.length;
int i, j;
for(i = 1; i < n; i++) {
int temp = a[i];
int low = 0;
int high = i - 1;
while(low <= high) {
int mid = low + (high - low)/2; // 防溢出
if(a[mid] > temp) {
high = mid - 1;
} else {
low = mid + 1;
}
}
for(j = i - 1; j >= low; j--) {
a[j + 1] = a[j]; //元素后移
}
a[low] = temp;
}
}
- 测试结果
public static void main(String[] args) {
int[] a = {4, 3, 2, 5, 1};
binaryInsertSort(a);
for(int i : a) {
System.out.println(i);
}
}
3、希尔排序算法
希尔排序实质上是采用分组插入的方法。先将整个待排序序列分割成几组,从而减少直接插入排序的数据量,对每组头尾分别进行对比换位,然后增加每组的数据量,重新分组。这样当经过几次分组排序后,整个序列就基本有序,再对整体进行一次直接插入排序。
- 代码实现
public static void sort(int[] array) {
int n = array.length;
int h = 1;
while(h < n/3) h = 3 * h + 1;
while(h >= 1) {
for(int i = h; i < n; i++) {
for(int j = i; j >= h && (array[j] < array[j - h]); j -= h) {
int temp = array[j];
array[j] = array[j - h];
array[j - h] = temp;
}
}
h /= 3;
}
}