几个面试可能会用到的排序算法

来源:互联网 发布:淘宝要交多少保证金 编辑:程序博客网 时间:2024/04/26 19:39
/***快速排序*/private static void quickSort(int[] iarr, int l, int h) {if (l >= h)return;int lIndex = l;int hIndex = h;int currentIndex = lIndex;while (lIndex != hIndex) {while (iarr[currentIndex] < iarr[hIndex]) {hIndex--;}swapArr(iarr, hIndex, currentIndex);currentIndex = hIndex;while (iarr[currentIndex] > iarr[lIndex]) {lIndex++;}swapArr(iarr, lIndex, currentIndex);currentIndex = lIndex;}quickSort(iarr, l, --lIndex);quickSort(iarr, ++hIndex, h);}/***冒泡排序*/private static void bubleSort(int[] arr) {int length = arr.length;for (int i = 1; i < length; i++) {for (int j = 0; j < length - i; j++) {if (arr[j] > arr[j + 1]) {swapArr(arr, j, j + 1);}}printArr(arr);}}/***选择排序*/private static void selectSort(int[] arr) {int length = arr.length;for (int i = 0; i < length - 1; i++) {for (int j = i + 1; j < length; j++) {if (arr[i] > arr[j]) {swapArr(arr, i, j);}}}}/***插入排序*/private static void insertSort(int[] arr) {int length = arr.length;for (int i = 1; i < length; i++) {int tmp = arr[i];int j = i - 1;while (j >= 0 && (tmp < arr[j])) {arr[j + 1] = arr[j];j--;}arr[j + 1] = tmp;}}/***希尔排序*/private static void shellSort(int[] arr) {int length = arr.length;int h = length / 2;while (h > 0) {for (int i = h; i < length; i += h) {int tmp = arr[i];int j = i - h;while (j >= 0 && (tmp < arr[j])) {arr[j + h] = arr[j];j -= h;}arr[j + h] = tmp;}h /= 2;}}/***堆排序,第一步构建大顶堆,第二步将0位置与末尾转换位置,有序堆从末尾开始,由右向左扩增*/for (int i = 0; i < iarr.length; i++) {createMaxHeap(iarr, iarr.length - 1 - i);swapArr(iarr, 0, iarr.length - 1 - i);}private static void createMaxHeap(int[] arr, int lastIndex) {for (int i = (lastIndex - 1) / 2; i >= 0; i--) {int k = i;while ((k * 2 + 1) <= lastIndex) {int biggerIndex = k * 2 + 1;if (biggerIndex + 1 <= lastIndex) {if (arr[biggerIndex] <= arr[biggerIndex + 1]) {biggerIndex++;}}if (arr[k] <= arr[biggerIndex]) {swapArr(arr, k, biggerIndex);k = biggerIndex;} else {break;}}}}

0 0
原创粉丝点击