本文共 2855 字,大约阅读时间需要 9 分钟。
先给代码,再给过程视频:
1 package com.dyi.wyb.sort; 2 3 import java.awt.Color; 4 import java.awt.Graphics; 5 import java.util.Random; 6 7 import javax.swing.*; 8 9 public class InsertionSort extends JFrame { 10 /** 11 * 12 */ 13 private static final long serialVersionUID = 1L; 14 /** 15 * main method 16 * 17 * @param args 18 * [] 19 * @author stagebo 20 */ 21 static int[] arr = getArray(1000); 22 static InsertionSort show; 23 public static void main(String[] args) { 24 show=new InsertionSort("插入排序"); 25 insertionSort(arr); 26 } 27 28 /** 29 * introduction:algorithms of insertionSort 30 * 31 * @param arr 32 * [] 33 * @return void 34 * 35 */ 36 public static void insertionSort(int[] arr) { 37 for (int j = 1; j < arr.length; j++) { 38 int key = arr[j]; 39 int i; 40 for (i = j - 1; i >= 0 && arr[i] > key; i--) { 41 arr[i + 1] = arr[i]; 42 try{Thread.sleep(5);}catch(Exception e){} 43 show.repaint(); 44 } 45 arr[i + 1] = key; 46 } 47 } 48 49 /** 50 * function: print array 51 * 52 * @param arr 53 * @param str 54 */ 55 public static void printArray(int[] arr, String str) { 56 System.out.print(str + ":"); 57 for (int i : arr) { 58 System.out.print(i + "--"); 59 } 60 System.out.println(); 61 } 62 63 /** 64 * constructor,initial the panel 65 */ 66 public InsertionSort(String title) { 67 setTitle(title); 68 setLocation(20, 20); 69 setSize(1000, 600); 70 setVisible(true); 71 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 72 } 73 74 public void paint(Graphics g) { 75 for (int i = 0; i < arr.length; i++) { 76 g.setColor(Color.BLACK); 77 g.drawLine(i, 600, i, 600-arr[i]); 78 g.setColor(Color.WHITE); 79 g.drawLine(i, 0,i, 600-arr[i]); 80 } 81 } 82 83 /** 84 * return a random value array 85 * 86 * @param length 87 * @return array[length] 88 */ 89 public static int[] getArray(int length) { 90 int[] re = new int[length]; 91 for (int i = 0; i < re.length; i++) 92 re[i] = i / 2; 93 for (int i = 0; i < re.length; i++) { 94 int index1 = new Random().nextInt(length); 95 for (int j = 0; j < 3; j++) { 96 int temp = re[i]; 97 re[i] = re[index1]; 98 re[index1] = temp; 99 }100 }101 return re;102 }103 }
插图,
插入排序的时间复杂度T(n)=O(n2),和冒泡排序半斤八两。
黑夜给了我黑色的眼睛,我却用它寻找光明转载地址:http://nxqtx.baihongyu.com/