- -----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
JAVA中的排序算法一般主要有四种方法:快速排序法、冒泡法、选择排序法、插入排序法。
快速排序法主要是运用了Arrays中的一个方法Arrays.sort()实现。
冒泡法是运用遍历数组进行比较,通过不断的比较将最小值或者最大值一个一个的遍历出来。
选择排序法是将数组的第一个数据作为最大或者最小的值,然后通过比较循环,输出有序的数组。
插入排序是选择一个数组中的数据,通过不断的插入比较最后进行排序。
快速排序法、
- public int[] quickSort(int[] result) {
- quick(result, 0, result.length - 1);
- return result;
- }
- <pre name="code" class="java">private void quick(int[] array, int startIndex, int endIndex) {
- int pIndex = startIndex;
- for (int i = startIndex + 1; i <= endIndex; i ++) {
- if (array[i] < array[pIndex]) {
- int temp = array[i];
- for (int j = i; j > pIndex; j --) {
- array[j] = array[j - 1];
- }
- array[pIndex] = temp;
- pIndex ++;
- }
- }
- if (pIndex - startIndex > 1) {
- quick(array, startIndex, pIndex - 1);
- }
- if (endIndex - pIndex > 1) {
- quick(array, pIndex + 1, endIndex);
- }
- }
冒泡排序法
比较n轮,每一轮都把最大元素移动到数组后端。
- public int[] bubbleSort(int[] result) {
- for (int i = 0; i < ARRAYSIZE; i ++) {
- for (int j = i + 1; j < ARRAYSIZE; j ++) {
- if (result[i] > result[j]) {
- swap(result, i, j);
- }
- }
- }
- return result;
- }
选择排序法
- public int[] simpleSelectionSort(int[] result) {
- int minIndex = 0;
- for (int i = 0; i < result.length; i ++) {
- minIndex = i;
- for (int j = i + 1; j < result.length; j ++) {
- if (result[j] < result[minIndex]) {
- minIndex = j;
- }
- }
- swap(result, minIndex, i);
- }
- return result;
- }
- private void swap(int[] arr, int i, int j) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
插入排序法
原理与插入排序类似,不同点在于寻找插入位置的时候,采取的是折半查找方法
- public int[] binsertSort(int[] result) {
- for (int i = 1; i < ARRAYSIZE; i ++) {
- if (result[i] < result[0]) {
- int temp = result[i];
- for (int j = i - 1; j >= 0; j --) {
- result[j + 1] = result[j];
- }
- result[0] = temp;
- } else if (result[i] < result[i - 1]) {
- int larrange = 0;
- int rarrange = i - 1;
- while (rarrange - larrange > 1) {
- int p = (rarrange + larrange + 1)/2;
- if (result[i] < result[p]) {
- rarrange = p;
- } else {
- larrange = p;
- }
- }
- int temp = result[i];
- for (int j = i - 1; j >= larrange + 1; j --) {
- result[j + 1] = result[j];
- }
- result[larrange + 1] = temp;
- }
- }
- return result;
- }