八种排序算法

1.插入排序—直接插入排序(Straight Insertion Sort)

算法逻辑:

代码实现:

 1 public static void InsertSort(int a[]) {
 2         int n = a.length;
 3         for (int i = 1; i < n; i++) {
 4             int j = i - 1;
 5             int x = a[i];        
 6             while (j >= 0 && x < a[j]) {
 7                 a[j + 1] = a[j];
 8                 j--;                   //元素后移
 9             }
10             a[j + 1] = x;         //插入到正确位置
11         }
12         System.out.println(Arrays.toString(a));
13     }

2、希尔排序


static void ShellSort(int array[]) {
int len = array.length;
for (int h = len / 2; h > 0; h = h / 2) {
for (int i = h; i < len; i++) {
int temp = array[i];
int j = i;
if (array[j] < array[j - h]) {
while (j - h >= 0 && array[j] < array[j - h]) {
array[j] = array[j-h];
j -= h;
}
array[j] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}

 

posted @ 2021-01-21 13:05  乐易196  阅读(45)  评论(0)    收藏  举报