标签:
转载自:http://www.cnblogs.com/sevenyuan/archive/2009/12/04/1616897.html
冒泡排序、快速排序、选择排序、插入排序、希尔排序,甚至还有基数排序、鸡尾酒排序、桶排序、鸽巢排序、归并排序等。
1 代码 2 3 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package test.sort; 4 import java.util.Random; 5 //Java实现的排序类 6 public class NumberSort { 7 //私有构造方法,禁止实例化 8 private NumberSort() { 9 super(); 10 } 11 //冒泡法排序 12 public static void bubbleSort(int[] numbers) { 13 int temp; // 记录临时中间值 14 int size = numbers.length; // 数组大小 15 for (int i = 0; i < size - 1; i++) { 16 for (int j = i + 1; j < size; j++) { 17 if (numbers[i] < numbers[j]) { // 交换两数的位置 18 temp = numbers[i]; 19 numbers[i] = numbers[j]; 20 numbers[j] = temp; 21 } 22 } 23 } 24 } 25 //快速排序 26 public static void quickSort(int[] numbers, int start, int end) { 27 if (start < end) { 28 int base = numbers[start]; // 选定的基准值(第一个数值作为基准值) 29 int temp; // 记录临时中间值 30 int i = start, j = end; 31 do { 32 while ((numbers[i] < base) && (i < end)) 33 i++; 34 while ((numbers[j] > base) && (j > start)) 35 j--; 36 if (i <= j) { 37 temp = numbers[i]; 38 numbers[i] = numbers[j]; 39 numbers[j] = temp; 40 i++; 41 j--; 42 } 43 } while (i <= j); 44 if (start < j) 45 quickSort(numbers, start, j); 46 if (end > i) 47 quickSort(numbers, i, end); 48 } 49 } 50 //选择排序 51 public static void selectSort(int[] numbers) { 52 int size = numbers.length, temp; 53 for (int i = 0; i < size; i++) { 54 int k = i; 55 for (int j = size - 1; j > i; j--) { 56 if (numbers[j] < numbers[k]) 57 k = j; 58 } 59 temp = numbers[i]; 60 numbers[i] = numbers[k]; 61 numbers[k] = temp; 62 } 63 } 64 //插入排序 65 // @param numbers 66 public static void insertSort(int[] numbers) { 67 int size = numbers.length, temp, j; 68 for (int i = 1; i < size; i++) { 69 temp = numbers[i]; 70 for (j = i; j > 0 && temp < numbers[j - 1]; j--) 71 numbers[j] = numbers[j - 1]; 72 numbers[j] = temp; 73 } 74 } 75 //归并排序 76 public static void mergeSort(int[] numbers, int left, int right) { 77 int t = 1;// 每组元素个数 78 int size = right - left + 1; 79 while (t < size) { 80 int s = t;// 本次循环每组元素个数 81 t = 2 * s; 82 int i = left; 83 while (i + (t - 1) < size) { 84 merge(numbers, i, i + (s - 1), i + (t - 1)); 85 i += t; 86 } 87 if (i + (s - 1) < right) 88 merge(numbers, i, i + (s - 1), right); 89 } 90 } 91 //归并算法实现 92 private static void merge(int[] data, int p, int q, int r) { 93 int[] B = new int[data.length]; 94 int s = p; 95 int t = q + 1; 96 int k = p; 97 while (s <= q && t <= r) { 98 if (data[s] <= data[t]) { 99 B[k] = data[s]; 100 s++; 101 } else { 102 B[k] = data[t]; 103 t++; 104 } 105 k++; 106 } 107 if (s == q + 1) 108 B[k++] = data[t++]; 109 else 110 B[k++] = data[s++]; 111 for (int i = p; i <= r; i++) 112 data[i] = B[i]; 113 } 114 115 }
标签:
原文地址:http://www.cnblogs.com/liyuhui21310122/p/4480348.html