1、插入排序代码: public class InsertionSort { public static void main(String[] args) { int[] source = new int[]{4,2,1,6,3,6,0,-5,1,1}; int j; for(int i=1; i <source.length; i++) { if(source[i] < source[i-1]) { int temp = source[i]; //与待插入数据比较扫描的同时进行后移 for(j=i-1; (j>=0 && (temp < source[j])); j--) { source[j+1] = source[j]; } source[j+1] = temp; } } } } } 2、希尔排序代码: private static void shellSort(int[] source,int d) { int j,temp; //希尔排序的代码只是再插入排序的基础上增加了步长d变量 for(int i=d + 1; i<source.length; i++) { if(source[i] < source[i-d]) { temp = source[i]; //与待插入数据比较扫描的同时进行后移 for(j=i-d; (j>=0 && temp < source[j]); j=j-d) { source[j+d] = source[j]; } source[j+d] = temp; } } } 3、冒泡排序代码: public class BubbleSort { public static void main(String[] args) { int[] source = new int[]{3,9,6,2,5,1}; for(int i=1; i<source.length; i++) { //对当前无序区进行,从后向前扫描 for(int j=source.length-1; j>i; j--) { if(source[j] < source[j-1]) { int temp = source[j]; source[j] = source[j-1]; source[j-1] = temp; } } } } } 4、快速排序代码: public class QuickSort { public static void main(String[] args) { int[] s = {1,3,9,3,2,5,7,6,10,33}; QuickSort(s, 0, s.length-1); } private static void QuickSort(int[] source,int low,int high) { int pivotpos; if(low < high) { pivotpos = partition(source,low,high); QuickSort(source,low,pivotpos-1); QuickSort(source,pivotpos+1,high); } } private static int partition(int[] source,int low,int high) { int i,j,x; int pos = low; if(low < high) { i = low; j = high; x = source[i]; /* 快速排序通过两层while循环来实现, 内层循环只能确保至多从右边和左边各交换一次顺序, 外层循环确保在没有完全有序前一直进行左右间歇扫描排序 */ while(i < j) { /* 直到找到右边小于基准的位置,并将该值放到之前的基准位置, 该值得位置充当基准位置,但是基准值是不变的一直都是x */ while(i < j && source[j] > x) { j--; } if(i < j) { source[i] = source[j]; i++; } /*直到找到左边大于基准的位置,并将该值放到之前的基准位置, 该值的位置充当基准位置,但是基准值是不变的一直都是x */ while(i < j && source[i] < x) { i++; } if(i < j) { source[j] = source[i]; j--; } } source[i] = x; pos = i; } return pos; } } 5、选择排序代码: public class SelectSort { public static void main(String[] args) { int[] source = new int[]{3,9,6,2,5,1}; for(int i=0; i<source.length; i++) { //从无序区,开始与当前位置进行逐个对比 for(int j=i+1; j<source.length; j++) { if(source[i] > source[j]) { int temp = source[i]; source[i] = source[j]; source[j] = temp; } } } } }
几种排序的java代码实现
猜你喜欢
转载自wchjwj.iteye.com/blog/2200041
今日推荐
周排行