首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java Swing 圖形化示範:選擇排序法對陣列排序完整程式

     編輯:Java 程式設計入門

程式功能

建立一個 Swing 視窗應用程式,包含兩個文字區域與兩個按鈕:

  1. 產生隨機數:產生 10 個 0~49 的隨機整數,顯示於上方文字區域。
  2. 排序:對陣列執行選擇排序(由大到小),結果顯示於下方文字區域。

核心排序邏輯

// 選擇排序:每趟找出未排序區間最大值,交換到區間末尾
for (int i = 1; i < array.length; i++) {
    int maxIdx = 0;
    for (int j = 1; j <= array.length - i; j++) {
        if (array[j] > array[maxIdx]) maxIdx = j;
    }
    // 交換
    int temp = array[array.length - i];
    array[array.length - i] = array[maxIdx];
    array[maxIdx] = temp;
}

完整原始碼

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

public class SelectSortDemo extends JFrame {
    private final int[] array = new int[10];
    private final JTextArea areaUnsorted = new JTextArea();
    private final JTextArea areaSorted = new JTextArea();

    public SelectSortDemo() {
        setTitle("選擇排序法示範");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 350);
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(5,5,5,5);
        c.weightx = 1.0;

        // 上方:未排序
        c.gridy = 0; c.weighty = 1.0;
        add(new JScrollPane(areaUnsorted), c);
        // 產生隨機數按鈕
        c.gridy = 1; c.weighty = 0;
        JButton btnGen = new JButton("產生隨機數");
        btnGen.addActionListener(e -> generateRandom());
        add(btnGen, c);
        // 下方:已排序
        c.gridy = 2; c.weighty = 1.0;
        add(new JScrollPane(areaSorted), c);
        // 排序按鈕
        c.gridy = 3; c.weighty = 0;
        JButton btnSort = new JButton("排序");
        btnSort.addActionListener(e -> doSort());
        add(btnSort, c);

        setVisible(true);
    }

    private void generateRandom() {
        Random r = new Random();
        areaUnsorted.setText("");
        for (int i = 0; i < array.length; i++) {
            array[i] = r.nextInt(50);
            areaUnsorted.append(array[i] + "  ");
        }
    }

    private void doSort() {
        areaSorted.setText("");
        // 選擇排序(遞減)
        for (int i = 1; i < array.length; i++) {
            int maxIdx = 0;
            for (int j = 1; j <= array.length - i; j++) {
                if (array[j] > array[maxIdx]) maxIdx = j;
            }
            int temp = array[array.length - i];
            array[array.length - i] = array[maxIdx];
            array[maxIdx] = temp;
        }
        for (int v : array) areaSorted.append(v + "  ");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SelectSortDemo::new);
    }
}

執行畫面

選擇排序執行畫面

教學重點

  • 選擇排序時間複雜度 O(n²),適合小規模資料教學。
  • Swing 元件佈局使用 GridBagLayout 彈性配置。
  • 事件處理採用 Lambda 表達式(Java 8+),簡化匿名類別寫法。
  • 隨機數產生使用 Random.nextInt(bound)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved