1、直接插入排序
1.1、基本介绍和思想
1.2、代码实现
public class InsertSort {
public static void main(String[] args) {
int[] arr = {9,4,2,6,3,7,4,1};
insertSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void insertSort(int[] arr) {
int insertVal = 0;
int insertIndex = 0;
for (int i = 1; i < arr.length; i++) {
insertVal = arr[i];
insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
int curIndex = insertIndex + 1;
if (insertIndex != i) {
arr[curIndex] = insertVal;
}
}
}
}
2、希尔排序
2.1、简单插入排序存在的问题
-
简单的插入排序可能存在的问题.
-
数组arr = {2,3,4,5,6,1}这时需要插入的数1(最小),这样的过程是: {2,3,4,5,6,6} {2,3,4,5,5,6} {2,3,4,4,5,6} {2,3,3,4,5,6} {2,2,3,4,5,6} {1,2,3,4,5,6} -
结论:当需要插入的数是较小的数时,后移的次数明显增多,对效率有影响.
2.2、希尔排序法介绍和基本思想
2.3、交换法代码
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
shellSort(arr);
}
public static void shellSort(int[] arr) {
int temp = 0;
int count = 0;
for (int gap = arr.length/2; gap >0 ; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
for (int j = i - gap; j >= 0; j -= gap) {
if (arr[j] > arr[j + gap]) {
temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
}
}
}
System.out.println("希尔排序第"+(++count)+"轮="+ Arrays.toString(arr));
}
}
}
2.4、移动法代码(推荐)
package com.ping.sort;
import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
shellSort2(arr);
System.out.println("排序后"+Arrays.toString(arr));
}
public static void shellSort2(int[] arr) {
int count = 0;
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
int j = i;
int temp = arr[j];
if(arr[j] <arr[j-gap]){
while(j - gap >= 0 && temp <arr[j-gap]){
arr[j] = arr[j-gap];
j -= gap;
}
arr[j] = temp;
}
}
}
}
}
|