赞
踩
package cn.tedu.straw.resource.sort; public class InsertionSort { public static void main(String[] args) { int[] arr = {64, 25, 12, 22, 11, 11, 23, 23, 45}; System.out.println("排序前数组:"); printArray(arr); insertionSort(arr); System.out.println("\n排序后数组:"); printArray(arr); } static void insertionSort(int[] arr) { int n = arr.length; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; // 将 arr[j] 大于 key 的元素往后移动 while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } static void printArray(int[] arr) { for (int value : arr) { System.out.print(value + " "); } System.out.println(); } }
package cn.tedu.straw.resource.sort; /** * 冒泡排序 */ public class BubbleSort { public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; System.out.println("排序前数组:"); printArray(arr); bubbleSort(arr); System.out.println("\n排序后数组:"); printArray(arr); } private static void bubbleSort(int[] arr) { int temp; for (int i = 1; i < arr.length; i++) { for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } private static void printArray(int[] arr) { for (int value : arr) { System.out.print(value + " "); } System.out.println(); } }
public class InsertSort { public static void main(String[] args) { int[] arr = {5, 2, 4, 6, 1, 3}; insertionSort(arr); System.out.println("Sorted array:"); for (int num : arr) { System.out.print(num + " "); } } public static void insertionSort(int[] arr) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; // Move elements of arr[0..i-1], that are greater than key, // to one position ahead of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。