几个排序算法
Posted liter7
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了几个排序算法相关的知识,希望对你有一定的参考价值。
emmm,这是给我自己看的。。。。
package com.gjjun.sorts; import java.util.Arrays; /** * @author gjjun * @date 2018/9/2 **/ public class Sorts { public static void main(String[] args) { int[] array = {5, 2, 3, 6, 1, 4, 7, 8}; Sorts sorts = new Sorts(); //直接插入排序 // sorts.insertSorts(array); //冒泡排序 // sorts.bubbleSorts(array); //选择排序 // sorts.selectSorts(array); //希尔排序 // sorts.shellSorts(array); //快速排序 // sorts.quickSorts(array); //堆排序 sorts.heapSorts(array); System.out.println(Arrays.toString(array)); } private void heapSorts(int[] array) { //1.建堆 for (int i = array.length / 2 - 1; i >= 0; i--) { heapAdjust(array, i, array.length); } System.out.println(Arrays.toString(array)); //2.筛选 for (int i = array.length - 1; i > 0; i--) { swap(array, i, 0); heapAdjust(array, 0, i); } } private void heapAdjust(int[] array, int i, int l) { int rcTemp = array[i]; for (int j = 2 * i + 1; j < l; j = j * 2 + 1) { if (j + 1 < l && array[j] < array[j + 1]) { j++; } if (array[j] > rcTemp) { array[i] = array[j]; i = j; } else { break; } } array[i] = rcTemp; } private void quickSorts(int[] array) { qSorts(array, 0, array.length - 1); } private void qSorts(int[] array, int low, int high) { if (low < high) { int pivotLoc = partition(array, low, high); qSorts(array, low, pivotLoc - 1); qSorts(array, pivotLoc + 1, high); } } private int partition(int[] array, int low, int high) { int pivotKey = array[low]; while (low < high) { while (low < high && array[high] >= pivotKey) { high--; } array[low] = array[high]; while (low < high && array[low] <= pivotKey) { low++; } array[high] = array[low]; } array[low] = pivotKey; return low; } private void shellSorts(int[] array) { int length = array.length; int temp; int gap = length / 2; while (gap > 0) { for (int i = gap; i < length; i++) { temp = array[i]; int preIndex = i - gap; while (preIndex >= 0 && array[preIndex] > temp) { array[preIndex + gap] = array[preIndex]; preIndex -= gap; } array[preIndex + gap] = temp; } gap /= 2; } } private void selectSorts(int[] array) { int length = array.length; for (int i = 0; i < length; i++) { int min = array[i]; int index = i; for (int j = i + 1; j < length; j++) { if (array[j] < min) { min = array[j]; index = j; } } swap(array, i, index); } } private void bubbleSorts(int[] array) { int length = array.length; for (int i = 0; i < length; i++) { for (int j = 0; j < length - i - 1; j++) { if (array[j] > array[j + 1]) { swap(array, j, j + 1); } } } } private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } /** * 直接插入排序 * * @param array */ private void insertSorts(int[] array) { int length = array.length; for (int i = 1; i < length; i++) { int key = array[i]; int j = i - 1; //后移 while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } } }
以上是关于几个排序算法的主要内容,如果未能解决你的问题,请参考以下文章