堆排序算法参考了下面的文章,在他的基础上改进了一点,原来有几个地方循环次数多了
https://www.cnblogs.com/Java3y/p/8639937.htmlpublic class TestThird { private static int[] ss = {334, 4, 532, 24, 147, 76, 735, 245, 734, 2356, 24, 334, 735}; public static void main(String[] args) { int len = ss.length; for (int i = 0; i < len; i++) { System.out.print(" " + ss[i]); } System.out.println(" "); // heapSort(ss, len); // sort(0, len - 1); // bubbleSort(ss, len); shellSort(len); for (int i = 0; i < len; i++) { System.out.print(" " + ss[i]); } } //冒泡排序 思想是相邻两个数两两比较,经过一轮排序确认一个最大值,下轮循环就少循环一次 private static void bubbleSort(int[] aa, int len) { for (int i = 0; i < len; i++) { for (int j = 1; j < len - i; j++) { if (aa[j] < aa[j - 1]) { int temp = aa[j - 1]; aa[j - 1] = aa[j]; aa[j] = temp; } } } } //快速排序 思想找一个基准,通常选数组中的第一个元素,把比基准大的放在他的右边,比基准小的放在它的左边, //最后基准的位置找到,这时,由基准的位置把数组分成了两部分,从新用上面方法,用到递归方法。 private static void sort(int left, int right) { if (left >= right) { return; } int index = quickSort(left, right); sort(index + 1, right); sort(left, index - 1); } //快速排序的步骤 private static int quickSort(int left, int right) { int key = ss[left]; while (left < right) { while (left < right && ss[right] >= key) { right--; } ss[left] = ss[right]; while (left < right && ss[left] <= key) { left++; } ss[right] = ss[left]; } ss[left] = key; return left; } //堆排序 堆排序算法参考了下面的文章,在他的基础上改进了一点,原来有几个地方循环次数多了
// https://www.cnblogs.com/Java3y/p/8639937.htmlprivate static void heapSort(int[] arr, int len) { madHeap(arr, len); int currentMaxIndex = len - 1; for (int i = 0; i < len; i++) { int temp = arr[0]; arr[0] = arr[len - 1 - i]; arr[len - 1 - i] = temp; heapAdjust(arr, 0, currentMaxIndex); currentMaxIndex--; } } //堆排序构建大根堆 private static void madHeap(int[] arr, int size) { for (int i = (size - 1) / 2; i >= 0; i--) { heapAdjust(arr, i, size); } } //调整堆使之成为大根堆 private static void heapAdjust(int[] arr, int index, int size) { int left = index * 2 + 1; int right = index * 2 + 2; int max = index; if (left < size) { if (arr[max] < arr[left]) { max = left; } } if (right < size) { if (arr[max] < arr[right]) { max = right; } } if (max != index) { int temp = arr[index]; arr[index] = arr[max]; arr[max] = temp; heapAdjust(arr, max, size); } } //希尔排序 private static void shellSort(int len) { int temp = 0; int d = len; //下面的两个while循环 都是希尔排序的实现,只是想法不一样,插入的方式不同 第一个循环次数少 while (true) { d = d / 2; for (int i = d; i < len; i++) { for (int j = i; j >= d; j = j - d) { if (ss[j] < ss[j - d]) { temp = ss[j]; ss[j] = ss[j - d]; ss[j - d] = temp; } } } if (d == 1) { break; } } while (true) { d = d / 2; for (int i = 0; i < d; i++) { for (int j = i + d; j < len; j = j + d) { for (int k = j - d; k >= 0; k = k - d) { if (ss[k + d] < ss[k]) { temp = ss[k]; ss[k] = ss[k + d]; ss[k + d] = temp; } } } } if (d == 1) { break; } } } }
java实现冒泡排序,快速排序,希尔排序,堆排序算法
最新推荐文章于 2022-03-25 11:32:09 发布