创建冒泡计数器

时间:2018-10-25 03:37:09

标签: java sorting bubble-sort

我正在尝试创建一个计数器,该计数器在每次交换数字时都会计数。我认为我走在正确的轨道上,但是我的计数器没有显示,但是它可以编译并正常运行。这段代码将所有数字从最小到最大排序,我需要计算一下它交换了多少次。

它需要放在bubblesort()方法中。我相信您每次移动时都必须将swapItems添加到+1来进行抵抗。如果有人可以在这里帮助我,将不胜感激。

左侧带有“>”的代码是该代码的反义部分。

// Sorting Application

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

public class Sort2 extends JFrame implements ActionListener{

   private TextField[] items = new TextField[6];
   private JButton btnSort, btnClear, btnReset;
   private TextField tmp;
   private Label status;

   private int pauseInterval = 100; // ms
    
   public static void main(String[] args) {
      new Sort2().setVisible(true);
   }
   
   public Sort2() {
      init();
   }

   public void init() {
      setTitle("Sorting Algorithms");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(440, 200);
      JPanel jp = new JPanel(new BorderLayout());
      jp.setPreferredSize(new Dimension(440, 200));
      jp.setBackground(Color.white);
      
      JPanel itemPanel = new JPanel();
      itemPanel.setBackground(Color.white);
      for (int i = 0; i < items.length; i++) {
         items[i] = new TextField(3); 
         items[i].setPreferredSize(new Dimension(30,40));
         itemPanel.add(items[i]);
      }
      initItems();
      itemPanel.add(new Label("Temp:"));
      tmp = new TextField(4);
      tmp.setPreferredSize(new Dimension(30,40));
      tmp.setEditable(false);
      itemPanel.add(tmp);
      itemPanel.add(new Label(""))
         .setPreferredSize(new Dimension(380, 65));
   
      JPanel buttonPanel = new JPanel();
      buttonPanel.setBackground(Color.white);
      btnSort = new JButton("Sort");
      btnReset = new JButton("Reset");
      btnClear = new JButton("Clear");
      btnSort.addActionListener(this);
      btnClear.addActionListener(this);
      btnReset.addActionListener(this);
      buttonPanel.add(btnSort); 
      buttonPanel.add(btnClear); 
      buttonPanel.add(btnReset);
      
      status = new Label("Wating ... ");
      status.setPreferredSize(new Dimension(380, 40));
      JPanel statusPanel = new JPanel();
      statusPanel.setBackground(Color.white);
      statusPanel.add(status, BorderLayout.SOUTH);
      
      jp.add(itemPanel, BorderLayout.NORTH);
      jp.add(buttonPanel, BorderLayout.CENTER);
      jp.add(statusPanel, BorderLayout.SOUTH);
      
      getContentPane().add(jp);
   }

   private void initItems() {
      for (int i = 0; i < items.length; i++) {
         items[i].setText((
            String.valueOf((int)(Math.random()*100))));
      }
   }

   private void pause(int ms) {
      try {
         Thread.sleep(ms);
      } 
      catch (InterruptedException e) {
         showStatus(e.toString());
      }
   }

   private void assign(TextField to, TextField from) {
      Color tobg = to.getBackground();
      to.setBackground(Color.green);
      pause(pauseInterval);
      to.setText(from.getText());
      pause(pauseInterval);
      to.setBackground(tobg);
   }

   private void swapItems(TextField t1, TextField t2) {
      assign(tmp,t1);
      assign(t1,t2);
      assign(t2,tmp);
   }
   
   private boolean greaterThan(TextField t1, TextField t2) {
      boolean greater;
      Color t1bg = t1.getBackground();
      Color t2bg = t2.getBackground(); 
      t1.setBackground(Color.cyan); 
      t2.setBackground(Color.cyan); 
      pause(pauseInterval);
      greater = Integer.parseInt(t1.getText()) < 
              Integer.parseInt(t2.getText());
      pause(pauseInterval);
      t1.setBackground(t1bg);
      t2.setBackground(t2bg);  
      return greater;
   }

>        private void bubbleSort() {
>         int currentCount = 0;
>           showStatus("Sorting ...");
>           boolean swap = true;
>           while (swap) {
>              swap=false;
>              for (int i = 0; i < items.length-1; i++) {
>                 if (greaterThan(items[i],items[i+1])) {
>                    swapItems(items[i],items[i+1]);
>                    swap=true;
>                    for (int step = 1; step <= items.length+1; step++) {
>                        currentCount = currentCount + 1;
>                    }
>                 }
>              } //for
>           } // while
>           showStatus("Sort complete" + " number of swaps = " + currentCount);
>        } // bubbleSort

   public void actionPerformed(ActionEvent e) {
      String command = e.getActionCommand();
      switch (command) {
         case "Clear":
            for (int i = 0; i < items.length; i++) {
               items[i].setText("");
            }
            break;
         case "Sort":
            bubbleSort();
            break;
         case "Reset":
            initItems();
            break;
         default:
            showStatus("Unrecognised button: " + e.toString());
      }
   }

   private void showStatus(String s) {
      status.setText(s);
   }
      
}

2 个答案:

答案 0 :(得分:0)

如果我理解正确,我认为问题是您有不必要的for循环(带有step变量的循环)。您所需要做的就是删除该循环,而只需添加以下内容:

currentCount += 1; 
// Alternatively, you could also do 'currentCount = currentCount + 1;' or 'currentCount++;'

因此,基本上,if方法中的bubbleSort()语句应如下所示:

if (greaterThan(items[i], items[i + 1])) {
    swapItems(items[i], items[i + 1]);
    swap = true;
    currentCount += 1;
}

答案 1 :(得分:0)

请找到计算交换的更新后的工作代码。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Counter extends JFrame implements ActionListener {

    private TextField[] items = new TextField[6];
    private JButton btnSort, btnClear, btnReset;
    private TextField tmp;
    private Label status;
    private JLabel cntLabel;

    private int pauseInterval = 100;

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        Counter f = new Counter();
        f.init();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public Counter() {
//      init();
    }

    public void init() {
        setTitle("Sorting Algorithms");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(440, 200);
        JPanel jp = new JPanel(new BorderLayout());
        jp.setPreferredSize(new Dimension(440, 200));
        jp.setBackground(Color.white);

        JPanel itemPanel = new JPanel(new FlowLayout());
        itemPanel.setBackground(Color.white);
        for (int i = 0; i < items.length; i++) {
            items[i] = new TextField(3);
            items[i].setPreferredSize(new Dimension(30, 40));
            itemPanel.add(items[i]);
        }

        initItems();

        itemPanel.add(new Label("Temp:"));
        tmp = new TextField(4);
        tmp.setPreferredSize(new Dimension(30, 40));
        tmp.setEditable(false);
        itemPanel.add(tmp);
        itemPanel.add(cntLabel).setPreferredSize(new Dimension(100, 65));


        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.white);
        btnSort = new JButton("Sort");
        btnReset = new JButton("Reset");
        btnClear = new JButton("Clear");
        btnSort.addActionListener(this);
        btnClear.addActionListener(this);
        btnReset.addActionListener(this);
        buttonPanel.add(btnSort);
        buttonPanel.add(btnClear);
        buttonPanel.add(btnReset);

        status = new Label("Wating ... ");
        status.setPreferredSize(new Dimension(380, 40));
        JPanel statusPanel = new JPanel();
        statusPanel.setBackground(Color.white);
        statusPanel.add(status, BorderLayout.SOUTH);

        jp.add(itemPanel, BorderLayout.NORTH);
        jp.add(buttonPanel, BorderLayout.CENTER);
        jp.add(statusPanel, BorderLayout.SOUTH);

        getContentPane().add(jp);
    }

    private void initItems() {
        for (int i = 0; i < items.length; i++) {
            items[i].setText((String.valueOf((int) (Math.random() * 100))));
        }
//      if(null!=swapLabel)
//          swapLabel.setText("");
        cntLabel = new JLabel("0");
    }

    private void pause(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            showStatus(e.toString());
        }
    }

    private void assign(TextField to, TextField from) {
        Color tobg = to.getBackground();
        to.setBackground(Color.green);
        pause(pauseInterval);
        to.setText(from.getText());
        pause(pauseInterval);
        to.setBackground(tobg);
    }

    private void swapItems(TextField t1, TextField t2) {
        assign(tmp, t1);
        assign(t1, t2);
        assign(t2, tmp);
    }

    private boolean greaterThan(TextField t1, TextField t2) {
        boolean greater;
        Color t1bg = t1.getBackground();
        Color t2bg = t2.getBackground();
        t1.setBackground(Color.cyan);
        t2.setBackground(Color.cyan);
        pause(pauseInterval);
        greater = Integer.parseInt(t1.getText()) < Integer.parseInt(t2.getText());
        pause(pauseInterval);
        t1.setBackground(t1bg);
        t2.setBackground(t2bg);
        return greater;
    }

    private void bubbleSort() {
        int currentCount = 0;
        int n = 0;
        showStatus("Sorting ...");
        boolean swap = true;
        while (swap) {
            swap = false;
            for (int i = 0; i < items.length - 1; i++) {
                if (greaterThan(items[i], items[i + 1])) {
                    swapItems(items[i], items[i + 1]);
                    swap = true;
                    currentCount++;
                }
            } // for
        } // while
        showStatus("Sort complete : Swap count = " + currentCount);
    } // bubbleSort

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        switch (command) {
        case "Clear":
            for (int i = 0; i < items.length; i++) {
                items[i].setText("");
            }
            cntLabel = new JLabel("0");
            break;
        case "Sort":
            bubbleSort();
            break;
        case "Reset":
            initItems();
            break;
        default:
            showStatus("Unrecognised button: " + e.toString());
        }
    }

    private void showStatus(String s) {
        status.setText(s);
    }

}