package algorithm; /** * @author: kimt * @Version: 1.0 * @date: 2017年11月9日 上午11:13:04 * @Description: 各种排序算法 */ public class SortALG { public static void main(String[] args) { int[] a = { 5, 1, 7, 3, 2, 4 }; bubbleSort(a); printArr(a); } /** * 插入排序之:快速插入排序 * * 基本思想:将待排序表看做是左、右两部分,其中左边为有序区,右边为无序区,整个排序过程就是依次将右边无序区中的记录按关键字大小插入到左边有序区中, * 以构成新的有序区,直到全部记录都排好序。 * * 适用情况:直接插入排序算法简单、容易实现,适用于待排序记录基本有序或待排序记录较少时。 * 当待排序的记录个数较多时,大量的比较和移动操作使直接插入排序算法的效率降低 时间复杂度:T(n)=O(n²) 空间复杂度:S(n)=O(1) * * 该算法思想:将待排序数组划分为左(已排序)右(待排序)两个区间,选取右(待排序)区间a[1]->a[n-1]作为比较条件(a[i]),与a[i-1 * ]->a[0]作比较(为a[j]); * 如果发现a[i]>a[j],则跳出比较内循环;否则进行移动操作,a[j+1]=a[j];跳出循环后,将a[i](即temp)进行排序(插入相应位置 * ),a[j+1]=temp * * @param array * 待排序数组 */ public static void insertSort(int[] array) { int temp = 0; int j, i; for (i = 1; i < array.length; i++) { temp = array[i]; for (j = i - 1; j >= 0; j--) { if (temp < array[j]) array[j + 1] = array[j]; else break; } array[j + 1] = temp; } } /** * 选择排序之:简单选择排序 * 基本思想:将数据元素序列分成有序区和无序区两部分。每趟排序都从无序区中选取出关键字最小的数据元素放在有序区的最后(无序区的最前), * 直到全部数据元素排序完毕。 * * 时间复杂度:T(n)=O(n²) * 空间复杂度:S(n)=O(1) * * @param array * 待排序数组 */ public static void selectSort(int[] array) { int i, j; int min, temp; for (i = 0; i < array.length - 1; i++) { min = i; for (j = i + 1; j < array.length; j++) { if (array[j] < array[min]) min = j; } if (min != i) { temp = array[i]; array[i] = array[min]; array[min] = temp; } } } /** * 交换排序之:冒泡排序 * 基本思想:每趟不断将记录两两比较,若发现逆序,则交换两个记录,使关键字较小(大)的元素逐渐从右(左)移向左(右)部 * * 时间复杂度为O(n2) * s(n)=O(1) * @param array 待排序数组 */ public static void bubbleSort(int[] array) { int i, j, temp; //一旦下趟没有交换发生,则该序列已排好序,可以提前结束排序 boolean exchange; for (i = 0; i < array.length - 1; i++) {// 最多length-1趟排序 exchange = false; //方式一:往大(右)的方向冒泡,好记,但是多了一步计算操作(array.length -i) /*for (j = 1; j < array.length -i; j++) { if (array[j-1] > array[j]) { temp = array[j-1]; array[j-1] = array[j]; array[j] = temp; exchange = true; } }*/ //方式二:往小(左)的方向冒泡 for (j = array.length - 1; j > i; j--) { if (array[j] < array[j - 1]) { temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; exchange = true; } } if (!exchange) break; } } /** * 打印数组 * * @param arr * 待打印数组 */ public static void printArr(int[] arr) { if (arr == null) throw new IllegalArgumentException("数组不能为null"); for (int a : arr) { System.out.print(a + " "); } } }
复习三种最基本的排序算法
最新推荐文章于 2022-04-17 16:44:44 发布