您好,欢迎访问一九零五行业门户网

排序算法详解

所谓排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作。排序算法,就是如何使得记录按照要求排列的方法。排序算法在很多领域得到相当地重视,尤其是在大量数据的处理方面。一个优秀的算法可以节省大量的资源。
simple insertion sort 插入排序
/** * 将位置p上的元素向左移动,直到它在前p+1个元素中的正确位置被找到的地方 * @param a an array of comparable items */public static <anytype extends comparable<? super anytype>> void insertionsort(anytype[] a) { int j; for (int p = 1; p < a.length; p++) { anytype tmp = a[p]; for (j = p; j > 0 && tmp.compareto(a[j-1]) < 0; j--) { a[j] = a[j-1]; } a[j] = tmp; } system.out.println(arrays.tostring(a));}
shell sort 希尔排序
/** * @param a an array of comparable items */public static <anytype extends comparable<? super anytype>> void shellsort(anytype[] a) { int j; for (int gap = a.length / 2; gap > 0; gap /= 2) { for (int i = gap; i < a.length; i++) { anytype tmp = a[i]; for (j = i; j >= gap && tmp.compareto(a[j - gap]) < 0; j -= gap) { a[j] = a[j - gap]; } a[j] = tmp; } } system.out.println(arrays.tostring(a)); }
binary sort 二分排序
/** * @param a an array of comparable items */public static <anytype extends comparable<? super anytype>> void binarysort(anytype[] a) { integer i,j; integer low,high,mid; anytype temp; for(i=1;i<a.length;i++){ temp=a[i]; low=0; high=i-1; while(low<=high){ mid=(low+high)/2; if(temp.compareto(a[mid]) < 0) { high=mid-1; } else { low=mid+1; } } for(j=i-1;j>high;j--) a[j+1]=a[j]; a[high+1]=temp; } system.out.println(arrays.tostring(a)); }
bubble sort 冒泡排序
/** * @param a an array of comparable items */public static <anytype extends comparable<? super anytype>> void bubblesort(anytype[] a) { integer i,j; anytype temp; for(i=1;i<a.length;i++) { for(j=0;j<a.length-i;j++) { //循环找到下沉"气泡",每下沉一位,下次比较长度较小一位 if(a[j].compareto(a[j+1]) > 0) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; //将"气泡"下沉到当前比较的最后一位 } } } system.out.println(arrays.tostring(a)); }
selection sort 选择排序
/** * @param a an array of comparable items */public static <anytype extends comparable<? super anytype>> void selectsort(anytype[] a) { integer i,j,min; anytype temp; for(i=0;i<a.length-1;i++) { temp=a[i]; min=i; //将当前位置元素当作最小值元素(其实是要将最小值元素交换到当前) for(j=i+1;j<a.length;j++) { if(temp.compareto(a[j]) > 0) { //用a[i]和后面所有元素逐个比较,找到最小指的下标并记录 temp=a[j]; //下一位小于前一位,则将下一位赋值给temp并继续往右移动比较 min=j; //最小值的下标,赋值给min } } a[min] = a[i]; //将最小值元素的和当前元素交换,使得当前元素为其后面所有元素中最小值 a[i] = temp; } system.out.println(arrays.tostring(a));
以上内容就是几种排序算法的教程,希望能帮助到大家。
相关推荐:
javascript基本常用排序算法的实例解析
php堆排序算法实例详解
php几种排序算法实例详解
其它类似信息

推荐信息