欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)插入排序算法可視化的示例代碼

 更新時間:2022年08月24日 09:26:15   作者:天人合一peng  
插入排序的算法描述是一種簡單直觀的排序算法。其原理是通過構建有序序列,對于未排序數(shù)據(jù),在已排序序列中從后向前掃描,找到相應位置并插入。本文將用Java語言實現(xiàn)插入排序算法并進行可視化,感興趣的可以了解一下

參考文章

圖解Java中插入排序算法的原理與實現(xiàn)

實現(xiàn)效果

示例代碼

import java.awt.*;
 
public class AlgoVisualizer {
 
    private static int DELAY = 40;
 
    private InsertionSortData data;
    private AlgoFrame frame;
 
    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
 
        // 初始化數(shù)據(jù)
        data = new InsertionSortData(N, sceneHeight);
 
        // 初始化視圖
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Insertion Sort Visualization", sceneWidth, sceneHeight);
 
            new Thread(() -> {
                run();
            }).start();
        });
    }
 
    public void run(){
 
        setData(0, -1);
 
        for( int i = 0 ; i < data.N() ; i ++ ){
 
            setData(i, i);
            for(int j = i ; j > 0 && data.get(j) < data.get(j-1) ; j --){
                data.swap(j,j-1);
                setData(i+1, j-1);
            }
        }
        setData(data.N(), -1);
 
    }
 
    private void setData(int orderedIndex, int currentIndex){
        data.orderedIndex = orderedIndex;
        data.currentIndex = currentIndex;
 
        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }
 
    public static void main(String[] args) {
 
        int sceneWidth = 800;
        int sceneHeight = 800;
        int N = 100;
 
        AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N);
    }
}
import java.awt.*;
import javax.swing.*;
 
public class AlgoFrame extends JFrame{
 
    private int canvasWidth;
    private int canvasHeight;
 
    public AlgoFrame(String title, int canvasWidth, int canvasHeight){
 
        super(title);
 
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
 
        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);
        pack();
 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
 
        setVisible(true);
    }
 
    public AlgoFrame(String title){
 
        this(title, 1024, 768);
    }
 
    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}
 
    // data
    private InsertionSortData data;
    public void render(InsertionSortData data){
        this.data = data;
        repaint();
    }
 
    private class AlgoCanvas extends JPanel{
 
        public AlgoCanvas(){
            // 雙緩存
            super(true);
        }
 
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
 
            Graphics2D g2d = (Graphics2D)g;
 
            // 抗鋸齒
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);
 
            // 具體繪制
            int w = canvasWidth/data.N();
            //AlgoVisHelper.setColor(g2d, AlgoVisHelper.Grey);
            for(int i = 0 ; i < data.N() ; i ++ ) {
                if (i < data.orderedIndex)  // 有序的位置紅色否則灰色
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);
                else
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Grey);
 
                if( i == data.currentIndex )   //當前
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Green);
                AlgoVisHelper.fillRectangle(g2d, i * w, canvasHeight - data.get(i), w - 1, data.get(i));
            }
        }
 
        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}
 
public class InsertionSortData {
 
    private int[] numbers;
    public int orderedIndex = -1;   // [0...orderedIndex) 是有序的
    public int currentIndex = -1;
 
    public InsertionSortData(int N, int randomBound){
 
        numbers = new int[N];
 
        for( int i = 0 ; i < N ; i ++)
            numbers[i] = (int)(Math.random()*randomBound) + 1;
    }
 
    public int N(){
        return numbers.length;
    }
 
    public int get(int index){
        if( index < 0 || index >= numbers.length)
            throw new IllegalArgumentException("Invalid index to access Sort Data.");
 
        return numbers[index];
    }
 
    public void swap(int i, int j) {
        if( i < 0 || i >= numbers.length || j < 0 || j >= numbers.length)
            throw new IllegalArgumentException("Invalid index to access Sort Data.");
 
        int t = numbers[i];
        numbers[i] = numbers[j];
        numbers[j] = t;
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
 
import java.lang.InterruptedException;
 
public class AlgoVisHelper {
 
    private AlgoVisHelper(){}
 
    public static final Color Red = new Color(0xF44336);
    public static final Color Pink = new Color(0xE91E63);
    public static final Color Purple = new Color(0x9C27B0);
    public static final Color DeepPurple = new Color(0x673AB7);
    public static final Color Indigo = new Color(0x3F51B5);
    public static final Color Blue = new Color(0x2196F3);
    public static final Color LightBlue = new Color(0x03A9F4);
    public static final Color Cyan = new Color(0x00BCD4);
    public static final Color Teal = new Color(0x009688);
    public static final Color Green = new Color(0x4CAF50);
    public static final Color LightGreen = new Color(0x8BC34A);
    public static final Color Lime = new Color(0xCDDC39);
    public static final Color Yellow = new Color(0xFFEB3B);
    public static final Color Amber = new Color(0xFFC107);
    public static final Color Orange = new Color(0xFF9800);
    public static final Color DeepOrange = new Color(0xFF5722);
    public static final Color Brown = new Color(0x795548);
    public static final Color Grey = new Color(0x9E9E9E);
    public static final Color BlueGrey = new Color(0x607D8B);
    public static final Color Black = new Color(0x000000);
    public static final Color White = new Color(0xFFFFFF);
 
    public static void strokeCircle(Graphics2D g, int x, int y, int r){
 
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g.draw(circle);
    }
 
    public static void fillCircle(Graphics2D g, int x, int y, int r){
 
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g.fill(circle);
    }
 
    public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){
 
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g.draw(rectangle);
    }
 
    public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){
 
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g.fill(rectangle);
    }
 
    public static void setColor(Graphics2D g, Color color){
        g.setColor(color);
    }
 
    public static void setStrokeWidth(Graphics2D g, int w){
        int strokeWidth = w;
        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    }
 
    public static void pause(int t) {
        try {
            Thread.sleep(t);
        }
        catch (InterruptedException e) {
            System.out.println("Error sleeping");
        }
    }
 
    public static void putImage(Graphics2D g, int x, int y, String imageURL){
 
        ImageIcon icon = new ImageIcon(imageURL);
        Image image = icon.getImage();
 
        g.drawImage(image, x, y, null);
    }
 
    public static void drawText(Graphics2D g, String text, int centerx, int centery){
 
        if(text == null)
            throw new IllegalArgumentException("Text is null in drawText function!");
 
        FontMetrics metrics = g.getFontMetrics();
        int w = metrics.stringWidth(text);
        int h = metrics.getDescent();
        g.drawString(text, centerx - w/2, centery + h);
    }
}

到此這篇關于Java實現(xiàn)插入排序算法可視化的示例代碼的文章就介紹到這了,更多相關Java插入排序內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java long 轉成 String的實現(xiàn)

    Java long 轉成 String的實現(xiàn)

    這篇文章主要介紹了Java long 轉成 String的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Java 中比較對象的用法小結

    Java 中比較對象的用法小結

    在 Java 中,比較對象的方法有多種多樣,每種都有其適用的場景,通過深入理解 equals() 方法、Comparable 接口和 Comparator 接口,我們能夠更好地處理對象之間的比較,使代碼更加靈活、清晰和健壯,本文給大家介紹Java 中比較對象的用法,感興趣的朋友一起看看吧
    2023-12-12
  • java實現(xiàn)外賣訂餐系統(tǒng)

    java實現(xiàn)外賣訂餐系統(tǒng)

    這篇文章主要為大家詳細介紹了java實現(xiàn)外賣訂餐系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-01-01
  • Java基礎之自動裝箱,注解操作示例

    Java基礎之自動裝箱,注解操作示例

    這篇文章主要介紹了Java基礎之自動裝箱,注解操作,結合實例形式分析了java拆箱、裝箱、靜態(tài)導入、注釋等相關使用技巧,需要的朋友可以參考下
    2019-08-08
  • 四個實例超詳細講解Java?貪心和枚舉的特點與使用

    四個實例超詳細講解Java?貪心和枚舉的特點與使用

    貪心算法是指,在對問題求解時,總是做出在當前看來是最好的選擇。也就是說,不從整體最優(yōu)上加以考慮,他所做出的是在某種意義上的局部最優(yōu)解,枚舉法的本質就是從所有候選答案中去搜索正確的解,枚舉算法簡單粗暴,他暴力的枚舉所有可能,盡可能地嘗試所有的方法
    2022-04-04
  • JAVA調用JavaScript方法代碼示例

    JAVA調用JavaScript方法代碼示例

    之前在一次機緣巧合的情況下,需要時用JAVA執(zhí)行js方法,查閱了一些文檔,找到了相關解決方法,這里和大家分享一下,這篇文章主要給大家介紹了關于JAVA調用JavaScript方法的相關資料,需要的朋友可以參考下
    2023-09-09
  • 通過Java代碼技巧改善性能

    通過Java代碼技巧改善性能

    在本篇文章里小編給大家分享了關于通過Java代碼技巧改善性能的相關知識點,需要的朋友們參考下。
    2019-05-05
  • 詳談jvm--Java中init和clinit的區(qū)別

    詳談jvm--Java中init和clinit的區(qū)別

    下面小編就為大家?guī)硪黄斦刯vm--Java中init和clinit的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • java數(shù)據(jù)結構循環(huán)隊列的空滿判斷及長度計算

    java數(shù)據(jù)結構循環(huán)隊列的空滿判斷及長度計算

    這篇文章主要為大家介紹了java數(shù)據(jù)結構循環(huán)隊列的空滿判斷及長度計算,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Spring JPA find單表查詢方法示例詳解

    Spring JPA find單表查詢方法示例詳解

    這篇文章主要為大家介紹了Spring JPA find單表查詢方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04

最新評論