排序算法之希尔(优化冒泡)排序

来源:互联网 发布:mm下载软件 编辑:程序博客网 时间:2024/04/26 06:28

希尔排序是用来优化其他算法的,进行分组,初始的gap等于n/2,然后依次减半,直到最后取1.这个1有点特别,如果直接放里面会导致死循环。在分组的for循环里面有点不方便,所以在后面进行for循环代码修正,单独写变量的增值。用if来解决这个死循环的问题。分组后进行冒泡,进行gap分组内的值-1此冒泡,同时进行优化,否则当gap=1时就是冒泡排序了,在组内排序,每次比完就加gap,跳过的比。希尔排序的核心思想就是分组,组内排序,再分组,---越来越有序,结合之前的算法,如果越有序就越快,来优化其他算法。

package cn.hncu.sorts;public class SortWay2 {//输出函数private static void print(int[] a) {for(int num:a){System.out.print(num+" ");}System.out.println();}//交换数组位置函数private static void swap(int[] a, int j, int i) {int temp;temp=a[i];a[i]=a[j];a[j]=temp;}//shellSort排序private static void shellSort(int[] a) {//进行分组,初始的gap=n/2,然后依次减半,到1为止for (int gap=(a.length+1)/2;gap>0;) {//分组冒泡   按理来说用冒泡还要进行优化,不然当gap=1就是冒泡排序了for (int i = 0; i < a.length-gap; i++) {//组内排序for (int j = i; j < a.length-gap; j+=gap) {if(a[j]>a[j+gap]){swap(a, j, j+gap);}}}//for循环的修正代码有点复杂,直接写在for里面不方便 单独写if(gap>1){gap=(gap+1)/2;}else if(gap==1){break;}}}public static void main(String[] args) {int[] a={21,22,5,7,86,57,9,-2,37,-8};//希尓排序shellSort(a);print(a);}}


0 0