1、冒泡排序
public static void sort(long[] array){ long tmp = 0; for (int i = 0; i < array.length - 1; i++) { //需要的遍历次数 for (int j = array.length - 1; j > i; j--) { if(array[j] < array[j - 1]){ tmp = array[j]; array[j] = array[j - 1]; array[j - 1] = tmp; } } } }
2、选择排序
public static void sort(long[] array){ int k = 0; long tmp = 0; for (int i = 0; i < array.length - 1; i++) { k = i; for (int j = i; j < array.length; j++) { if(array[j] < array[i]){ k = j; } } tmp = array[k]; array[k] = array[i]; array[i] = tmp; } }
3、插入排序
public static void sort(long[] array) { long tmp = 0; for (int i = 1; i < array.length; i++) { tmp = array[i]; int j = i; while(j > 0 && array[j - 1] >= tmp) { array[j] = array[j - 1]; j--; } array[j] = tmp; } }
4、希尔排序
public static void sort(long[] array) { int h = 1; //计算最大间隔 while(h < array.length / 3) { h = h * 3 + 1; } while(h > 0){ long tmp = 0; for (int i = h; i < array.length; i++) { tmp = array[i]; int j = i; while(j > h - 1 && array[j - h] >= tmp) { array[j] = array[j - h]; j -= h; } array[j] = tmp; } //减小间隔 h = (h - 1) / 3; } }
5、快速排序
/* * 划分数组 */ public static int partition(long array[],int left,int right,long point){ int leftPtr = left - 1; int rightPtr = right; while(true){ //循环将比关键字小的留在数组的左边 while(leftPtr < rightPtr && array[++leftPtr] < point); //循环将比关键字大的留在数组的右边 while(rightPtr > leftPtr && array[--rightPtr] > point); if(leftPtr >= rightPtr){ break; } else { long tmp = array[leftPtr]; array[leftPtr] = array[rightPtr]; array[rightPtr] = tmp; } } long tmp = array[right]; array[right] = array[leftPtr]; array[leftPtr] = tmp; return leftPtr; } public static void sort(long array[],int left,int right){ if(left - right >= 0){ return; } else { long point = array[right]; //获取划分点 int partition = partition(array, left, right, point); //对左边的再次进行划分 sort(array, left, partition - 1); //对右边的再次进行划分 sort(array, partition + 1, right); } }
本文出自 “12212886” 博客,请务必保留此出处http://12222886.blog.51cto.com/12212886/1950036
原文:http://12222886.blog.51cto.com/12212886/1950036