dh-Materialien
Java Projekte
// JavaProject SortingAlgorithms

// DataList.java

import java.awt.List;


class DataList {

    int vol; // Datenumfang
    List items;

    public DataList() {
        vol = 0;
        items = new List();
    }

    public void setDataVol(int value) {
        vol = value;
    }

    public boolean isInList(String txt, List list) {
        boolean result = false;
        int len = list.getItemCount();
        for (int i=0; i<len; i++) {
            if (txt.equals(list.getItem(i))) {
                result = true;
                break;
            }
        }
        return result;
    }

    public void createData(String str) {
        switch(str) {
        case "NUM":
            createNumData();
            break;
        case "TXT":
            createTxtData();
            break;
        }
    }

    public void createNumData() {
        items.removeAll();
        int maxvalue = 99999;
        int nextvalue;
        double f;
        String nextitem = " ";
        boolean found;
        for (int i=0; i<vol; i++) {
            found = false;
            while (!found) {
                f = 1 + Math.random()*123;
                nextvalue = (int) Math.round(maxvalue*Math.random()/f);
                nextitem = Integer.toString(nextvalue);
                if (!isInList(nextitem, items)) found = true;
            }
            if (found) items.add(" "+nextitem+"\n");
        }
    }

    public void createTxtData() {
        items.removeAll();
        int len;
        char ch;
        int max = 4;
        String nextitem;
        boolean found;
        for (int i=0; i<vol; i++) {
            found = false;
            nextitem = "";
            while (!found) {
                len = (int) (Math.round(max*Math.random()) + 1);
                for (int j=0; j<len; j++) {
                    ch = (char) ((int) 97 + 25*Math.random());
                    nextitem = nextitem.concat(Character.toString(ch));
                }
                if (!isInList(nextitem, items)) found = true;
            }
            if (found) items.add(" "+nextitem+"\n");
        }
    }
}



// Sorter.java

import
java.awt.List;


class Sorter implements Runnable {

    PFrame pframe;
    Thread sorting;

    DataList datalist;   // die jeweilige zufällig erzeugte Rohdatenliste
    List list;           // Liste aller zu sortierenden Elemente
    String typ;          // Datentyp der zu sortierenden Elemente
    int n;               // Anzahl der zu sortierenden Elemente
    String method;       // Sortiermethode
    int delta_t;         // Wartezeit zwischen zwei Sortier-Schritten
    boolean ready;       // ist der Sortiervorgang fertig?
    boolean interrupted; // wurde der Sortiervorgang abgebrochen?
    int i, j;            // Laufvariablen


    public Sorter(DataList datalist, PFrame pframe) {
        this.datalist = datalist;
        this.pframe = pframe;

        list = new List();

        delta_t = 100;
        ready = false;
        interrupted = false;
    }

    private void returnSingleElement() {
        list.removeAll();
        list.add(datalist.items.getItems()[0]);
        showSortedDataList();
        finishSorting();
    }

    public void sortData(String method, String typ) {
        sorting = new Thread(this);
        interrupted = false;
        ready = false;

        this.method = method;
        this.typ = typ;
        n = datalist.vol;
        list.removeAll();
        String[] items = datalist.items.getItems();
        for (int i=0; i<n; i++) list.add(items[i]);

        if (method == "Bubble") {j = n-2; i = 0;}

        sorting.start();
        pframe.pcontainer.label_info.setText("Fertig sortiert.");
    }

    public void stop() {
        try {
            interrupted = true;
        }
        catch (Exception exc) { }
    }

    public void showSortedDataList() {
        pframe.area_sorted.setText("");
        for (int k=0; k<n; k++) {
            pframe.area_sorted.append(list.getItem(k));
        }
    }

    public void finishSorting() {
            pframe.pcontainer.stopsort_button.setVisible(false);
            if (!interrupted) pframe.pcontainer.sort_button.setVisible(true);
            pframe.pcontainer.label_info.setVisible(true);
            if (interrupted) {
            pframe.pcontainer.label_info.setText("Vorgang abgebrochen.");
            pframe.pcontainer.sort_button.setVisible(true);
        }
    }

    public void setDelta_t(int value) {
        delta_t = value;
    }

    private String convertToIntStr(String str) {
        String result = str.replaceAll(" ", "");
        result = result.replaceAll("> ", "");
        result = result.replaceAll("# ", "");
        result = result.replaceAll("\n", "");
        return result;
    }

    private void exchangeItems(int i, int j) {
        String h = list.getItem(i).toString();
        list.replaceItem(list.getItem(j), i);
        list.replaceItem(h, j);
    }

    private void markItem(int i) {
        String h = list.getItem(i).toString().replace(" ", "> ");
        list.replaceItem(h, i);
    }

    private void pivotItem(int i) {
        String h = list.getItem(i).toString().replace(" ", "# ");
        h = h.replace("> ", "# ");
        list.replaceItem(h, i);
    }

    private void fixItem(int i) {
        String h = list.getItem(i).toString().replace(" ", "| ");
        h = h.replace("> ", "| ");
        h = h.replace("# ", "| ");
        list.replaceItem(h, i);
    }

    private void cleanItem(int i) {
        String h = list.getItem(i).toString().replace("> ", " ");
        h = h.replace("# ", " ");
        list.replaceItem(h, i);
    }

    private void cleanAllItems() {
        for (int i=0; i<n; i++) {
            String h = list.getItem(i).toString().replace("| ", " ");
            h = h.replace("> ", " ");
            list.replaceItem(h, i);
        }
    }

    private void markItems(int i, int j) {
        markItem(i);
        markItem(j);
        showSortedDataList();
        pause();
    }

    private boolean ItemsAreWellOrdered(int i, int j) {
        boolean result = false;
        if (typ == "TXT") {
            if (list.getItem(i).compareTo(list.getItem(j)) < 0) result = true;
        }

        if (typ == "NUM") {
            String substr1 = convertToIntStr(list.getItem(i));
            String substr2 = convertToIntStr(list.getItem(j));
            if (Integer.valueOf(substr1) < Integer.valueOf(substr2)) result = true;
        }
        return result;
    }

    private void pause() {
        try {
            Thread.sleep(delta_t);
        }
        catch (Exception exc) { }
    }

    public void performBubblesort() {
        // Bubblesort startet mit j = n-2; i = 0; (Zeile 56)
        if (!ItemsAreWellOrdered(i, i+1)) {
            exchangeItems(i, i+1);
        }
        showSortedDataList();

        i++;
        cleanItem(i-1);
        markItem(i);
        showSortedDataList();
        pause();

        if (i > j) {
            j--;
            i = 0;
        }
        pause();
        if ((j < 0)&&(i == 0)) {
            cleanAllItems();
            showSortedDataList();
            ready = true;
        }
    }

    public void performInsertionsort() {
        int i, j = 0;
        list.add(" \n");

        for (i=1; i<n; i++) {
            list.replaceItem(list.getItem(i), n);
            pause();
            cleanItem(i-1);
            markItem(i);
            showSortedDataList();
            pause();
            list.replaceItem(" \n", i);
            markItem(i);
            showSortedDataList();
            pframe.area_sorted.append("\n\n"+list.getItem(n));
            pause();

            j = i-1;
            while ((j >= 0)&&(ItemsAreWellOrdered(n, j))&&(!interrupted)) {
                list.replaceItem(list.getItem(j), j+1);
                list.replaceItem(" \n", j);
                markItem(i);
                j--;
                showSortedDataList();
                pframe.area_sorted.append("\n\n"+list.getItem(n));
                pause();
            }
            list.replaceItem(list.getItem(n), j+1);
            showSortedDataList();
            pause();
            if (interrupted) break;
        }
        cleanItem(n-1);
        showSortedDataList();
        list.remove(n);
        ready = true;
    }

    public void performQuicksort(int pleft, int pright) {
        int pl = pleft;
        int pr = pright;
        if (pl < pr) {
            int i = pl;
            int j = pr-1;
            int p = pr;

            pivotItem(p);
            showSortedDataList();
            pause();

            while ((i < j)&&(!interrupted)) {
                markItems(i, j);
                while ((i < pright)&&(ItemsAreWellOrdered(i, p))&&(!interrupted)) {
                    cleanItem(i);
                    pivotItem(p);
                    i++;
                    markItems(i, j);
                    if (interrupted) break;
                }
                while ((pleft < j)&&(!ItemsAreWellOrdered(j, p))&&(!interrupted)) {
                    cleanItem(j);
                    pivotItem(p);
                    j--;
                    markItems(i, j);
                    if (interrupted) break;
                }
                pause();
                if ((i < j)&&(!interrupted)) {
                    exchangeItems(i, j);
                    pause();
                } else break;
                if (interrupted) break;
            }
            markItems(i, j);

            if (ItemsAreWellOrdered(p, i)) exchangeItems(i, p);
            fixItem(i);
            cleanItem(j);
            cleanItem(p);
            showSortedDataList();
            pause();

            if (!interrupted) {
                performQuicksort(pleft, i-1);
                performQuicksort(i+1, pr);
            }
        }
         
        if
((pl == 0)&&(pr == n-1)&&(!interrupted)) {
            for (i= 0; i<n; i++) cleanAllItems();
            showSortedDataList();
            ready = true;
        }
    }

    @Override
    public void run() {

        while ((!ready)&&(!interrupted)) {
            if (n == 1) {
                returnSingleElement();
                ready = true;
            } else {
                if (method == "Bubble") performBubblesort();
                if (method == "Insert") performInsertionsort();
                if (method == "Quick")  performQuicksort(0, n-1);
            }
        }

        if ((ready)||(interrupted)) finishSorting();
    }
}



// PContainer.java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


class PContainer extends Container
                 implements
DocumentListener, ActionListener, Runnable {
    private static final long serialVersionUID = 0L;

    Thread controlling = new Thread(this);

    DataList datalist;
    PFrame pframe;
    Sorter sorter;

    JLabel label_datatyp;
    JComboBox<String> box_datatyp;
    JLabel label_datavol;
    JTextField field_datavol;
    JLabel label_method;
    JComboBox<String> box_method;
    JButton create_button;
    JButton sort_button;
    JButton stopsort_button;
    JLabel label_step;
    JTextField field_step;
    JLabel label_stepunit;
    JLabel label_info;
    JLabel label_time;
    JLabel field_time;

    Color colbgr = new Color(240,240,240);

    public PContainer(DataList datalist, PFrame pframe, Sorter sorter) {
        this.datalist = datalist;
        this.pframe = pframe;
        this.sorter = sorter;

        setBackground(colbgr);
        setLayout(null);
        label_datatyp = new JLabel("Datentyp:");
        label_datatyp.setBounds(2,10,100,20);
        add(label_datatyp);
        box_datatyp = new JComboBox<String>();
        box_datatyp.setBounds(85,10,65,20);
        box_datatyp.addItem("NUM");
        box_datatyp.addItem("TXT");
        add(box_datatyp);

        label_datavol = new JLabel("Datenumfang:");
        label_datavol.setBounds(2,40,80,20);
        add(label_datavol);
        field_datavol = new JTextField();
        field_datavol.setBounds(85,40,66,22);
        field_datavol.setText("0");
        field_datavol.getDocument().addDocumentListener(this);
        add(field_datavol);

        label_method = new JLabel("Verfahren:");
        label_method.setBounds(2,70,60,20);
        add(label_method);
        box_method = new JComboBox<String>();
        box_method.setBounds(85,70,65,20);
        box_method.addItem("Bubble");
        box_method.addItem("Insert");
        box_method.addItem("Quick");
        add(box_method);

        create_button = new JButton("Daten erzeugen");
        create_button.setBounds(2,105,149,23);
        create_button.addActionListener(this);
        add(create_button);

        sort_button = new JButton("Daten sortieren");
        sort_button.setBounds(2,135,149,23);
        sort_button.addActionListener(this);
        sort_button.setVisible(false);
        add(sort_button);

        stopsort_button = new JButton("Abbrechen");
        stopsort_button.setBounds(2,165,149,23);
        stopsort_button.addActionListener(this);
        stopsort_button.setVisible(false);
        add(stopsort_button);

        label_step = new JLabel("Wartezeit:");
        label_step.setBounds(2,195,90,21);
        label_step.setVisible(false);
        add(label_step);
        field_step = new JTextField();
        field_step.setBounds(85,195,40,21);
        field_step.setText("100");
        field_step.getDocument().addDocumentListener(this);
        field_step.setVisible(false);
        add(field_step);
        label_stepunit = new JLabel("ms");
        label_stepunit.setBounds(128,195,20,20);
        label_stepunit.setVisible(false);
        add(label_stepunit);

        label_info = new JLabel("Fertig sortiert.");
        label_info.setBounds(2,222,200,20);
        label_info.setVisible(false);
        add(label_info);

        controlling.start();
    }

    public void actionPerformed(ActionEvent object) {
        if (object.getSource() == create_button) {
            String datatyp = box_datatyp.getSelectedItem().toString();
            if (datalist.vol != 0) {
                pframe.area_sorted.setText("");
                datalist.createData(datatyp);
                pframe.showUnsortedDataList();
                sort_button.setVisible(true);
                label_step.setVisible(true);
                field_step.setVisible(true);
                label_stepunit.setVisible(true);
                label_info.setVisible(false);
            } else {
                pframe.area_unsorted.setText("");
                pframe.area_sorted.setText("");
                pframe.area_sorted.setVisible(false);
                datalist.items.removeAll();
                sort_button.setVisible(false);
                label_step.setVisible(false);
                field_step.setVisible(false);
                label_stepunit.setVisible(false);
                label_info.setVisible(false);
            }
        }
        if (object.getSource() == sort_button) {
            String datamethod = box_method.getSelectedItem().toString();
            String datatyp = box_datatyp.getSelectedItem().toString();
            if (datalist.items.getItemCount() != 0) {
                pframe.area_sorted.setText("");
                pframe.area_sorted.setVisible(true);
                sorter.sortData(datamethod, datatyp);
                sort_button.setVisible(false);
                stopsort_button.setVisible(true);
                label_info.setVisible(false);
            }
        }
        if (object.getSource() == stopsort_button) {
            sorter.stop();
            stopsort_button.setVisible(false);
        }
    }

    public void handleException() {
        int volvalue;
        try {
            volvalue = Integer.parseInt(field_datavol.getText());
        }
        catch (Exception exc) {
            volvalue = 0;
        }
        datalist.setDataVol(volvalue);

        int deltavalue;
        try {
            deltavalue = Integer.parseInt(field_step.getText());
        }
        catch (Exception exc) {
            deltavalue = 100;
        }
        sorter.setDelta_t(deltavalue);
    }

    public void changedUpdate(DocumentEvent evt) {
        handleException();
    }

    public void insertUpdate(DocumentEvent evt) {
        handleException();
    }

    public void removeUpdate(DocumentEvent evt) {
        handleException();
    }

    @Override
    public void run() {
        boolean correct = true;
        while (true) {
            try {
                if (field_datavol.getText().length() != 0) {
                Integer.parseInt(field_datavol.getText());
                }
            }
            catch (Exception exc) {
                correct = false;
            }
            if ((datalist.vol == 0)&&(!correct)) {
                field_datavol.setText("");
                String title = "Eingabefehler";
                String message = "Es wird die Eingabe einer ganzen Zahl erwartet.";
                int em = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            if (datalist.vol > 500) correct = false;
            if (!correct) {
                field_datavol.setText("500");
                String title = "Begrenzter Datenumfang";
                String message = "Der Datenumfang darf nicht größer als 500 sein.";
                int em = JOptionPane.WARNING_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            if (datalist.vol < 0) correct = false;
            if (!correct) {
                field_datavol.setText("10");
                String title = "Eingabefehler";
                String message = "Es wird die Eingabe einer ganzen Zahl erwartet.";
                int em = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            try {
                if (field_step.getText().length() != 0) {
                    Integer.parseInt(field_step.getText());
                }
            }
            catch (Exception exc) {
                correct = false;
            }
            if ((sorter.delta_t == 100)&&(!correct)) {
                field_step.setText("100");
                String title = "Eingabefehler";
                String message = "Es wird die Eingabe einer ganzen Zahl erwartet.";
                int em = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            if (sorter.delta_t > 3000) correct = false;
            if (!correct) {
                field_step.setText("3000");
                String title = "Wartezeit zu groß gewählt";
                String message = "Die Wartezeit darf nicht größer als 3000ms sein.";
                int em = JOptionPane.WARNING_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            if (sorter.delta_t < 0) correct = false;
            if (!correct) {
                field_step.setText("100");
                String title = "Eingabefehler";
                String message = "Es wird die Eingabe einer ganzen Zahl erwartet.";
                int em = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(null, message, title, em);
                correct = true;
            }

            if (datalist.vol != datalist.items.getItemCount()) {
                stopsort_button.setVisible(false);
                sort_button.setVisible(false);
                label_step.setVisible(false);
                field_step.setVisible(false);                 
                label_stepunit.setVisible(false);
                label_info.setVisible(false);
                pframe.sorter.interrupted = true;
            }

            try {
                Thread.sleep(300);
            }
            catch (InterruptedException exc) { }
        }
    }
}



// PFrame.java

import java.awt.*;
import javax.swing.*;


class PFrame extends JFrame {
    private static final long serialVersionUID = 0L;

    DataList datalist;
    Sorter sorter;

    Image icon;
    JScrollPane pane_unsorted;
    JTextArea area_unsorted;
    JScrollPane pane_sorted;
    JTextArea area_sorted;
    PContainer pcontainer;

    JScrollBar scrollbar;
    Font font = new Font("Courier", Font.PLAIN, 12);

    public PFrame(int width, int height) {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(width, height);
        setLocationRelativeTo(null);
        setTitle("Sortieren von Daten");
        setResizable(false);
        icon = Toolkit.getDefaultToolkit().getImage("dh.png");
        setIconImage(icon);

        setLayout(null);
        area_unsorted = new JTextArea();
        area_unsorted.setEditable(false);
        area_unsorted.setFont(font);
        pane_unsorted = new JScrollPane(area_unsorted);
        pane_unsorted.setBounds(7, 8, 75, 248);
        add(pane_unsorted);

        area_sorted = new JTextArea();
        area_sorted.setEditable(false);
        area_sorted.setFont(font);
        pane_sorted = new JScrollPane(area_sorted);
        pane_sorted.setBounds(89, 8, 75, 248);
        area_sorted.setVisible(false);
        add(pane_sorted);

        datalist = new DataList();
        sorter = new Sorter(datalist, this);

        pcontainer = new PContainer(datalist, this, sorter);
        pcontainer.setBounds(170, 8, 300, 450);
        add(pcontainer);
        setBackground(pcontainer.colbgr);
    }

    public void showUnsortedDataList() {
        area_unsorted.setText("");
        for (int i=0; i<datalist.vol; i++) {
            area_unsorted.append(datalist.items.getItem(i));
        }
    }
}



// SortingAlgorithms.java

public class SortingAlgorithms {

    PFrame pframe;

    public SortingAlgorithms() {
            pframe = new PFrame(349, 301);
    }

    public static void main(String[] args) {
        SortingAlgorithms alg = new SortingAlgorithms();
        alg.pframe.setVisible(true);
    }
}


Download SortingAlgorithms