【开发者笔记】插入排序过程呈现之java内置GUI表示

2018-02-11 14:19:32来源:oschina作者:stagebo人点击

分享

先给代码,再给过程视频:


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 method16*17* @param args18* []19* @author stagebo20*/
21 static int[] arr = getArray(1000);22 static InsertionSort show;23 public static void main(String[] args) {24show=new InsertionSort("插入排序");25insertionSort(arr);26}27
28 /**
29* introduction:algorithms of insertionSort30*31* @param arr32* []33* @return void34*35*/
36 public static void insertionSort(int[] arr) {37for (int j = 1; j < arr.length; j++) {38int key = arr[j];39int i;40for (i = j - 1; i >= 0 && arr[i] > key; i--) {41 arr[i + 1] = arr[i];42 try{Thread.sleep(5);}catch(Exception e){}43show.repaint();44}45arr[i + 1] = key;46}47}48
49 /**
50* function: print array51*52* @param arr53* @param str54*/
55 public static void printArray(int[] arr, String str) {56System.out.print(str + ":");57for (int i : arr) {58System.out.print(i + "--");59}60System.out.println();61}62
63 /**
64* constructor,initial the panel65*/
66 public InsertionSort(String title) {67setTitle(title);68setLocation(20, 20);69setSize(1000, 600);70setVisible(true);71setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);72}73
74 public void paint(Graphics g) {75for (int i = 0; i < arr.length; i++) {76g.setColor(Color.BLACK);77g.drawLine(i, 600, i, 600-arr[i]);78g.setColor(Color.WHITE);79g.drawLine(i, 0,i, 600-arr[i]);80}81}82
83 /**
84* return a random value array85*86* @param length87* @return array[length]88*/
89 public static int[] getArray(int length) {90int[] re = new int[length];91for (int i = 0; i < re.length; i++)92re[i] = i / 2;93for (int i = 0; i < re.length; i++) {94int index1 = new Random().nextInt(length);95for (int j = 0; j < 3; j++) {96 int temp = re[i];97 re[i] = re[index1];98 re[index1] = temp;99} 100} 101return re; 102} 103 }插入排序以及显示面板代码

插图,插入排序过程显示视频连接


插入排序的时间复杂度T(n)=O(n2),和冒泡排序半斤八两。

微信扫一扫

第七城市微信公众平台