【问题标题】:Selection sort without a loop [closed]没有循环的选择排序[关闭]
【发布时间】:2013-04-13 23:03:12
【问题描述】:

对于这个程序,我想实现一个排序和搜索算法数组。该数组将填充随机数。然后我想将每个数组元素绘制为条形(制作类似于条形图的东西)。我在 GUI 中有一个步骤和运行按钮,该步骤应该使用选择排序。我遇到的问题是:我只知道如何使用循环进行选择排序。但是,我不能使用循环,因为我必须显示正在逐步排序的数组。谁能告诉我如何在没有循环的情况下进行选择排序?我将添加到目前为止的所有代码,因为这是我第一次发布任何东西,我想确保我是具体的。

数组查看器:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.util.Scanner;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ArrayViewer 
{
    static int[] array;
    static int size;

    public static void main(String[] args)
    {

        Scanner in=new Scanner(System.in);
        //ask for the size of the array until the user enters a size in the right range
        do
        {
            System.out.print("Enter the size of the array (should be between 10 and 80): ");
            size=in.nextInt();
        }
        while (size<10 || size>80);

        array= ArrayUtil.randomIntArray(size,100);//create a random array of given size and entries ranging from 0 to 100
        final ArrayComponent arrayComp= new ArrayComponent(array); //construct an arrayComponent with the random array   
        class ButtonListener implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                //I want the selection sort algorithm to go in here so I can just assign this to my stepButton.


            }
        }

        final JFrame frame=new JFrame("Sorting"); //create and setup the frame
        frame.setSize(1200,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel buttonPanel= new JPanel(); // panel to hold the buttons        
        JPanel panel=new JPanel(new BorderLayout()); // panel to hold the button panel and the array component; uses BorderLayout: read about it in the API

        JButton stepButton=new JButton("Step"); //button to go through the algorithm step by step
        JButton runButton=new JButton("Run"); //button to run the algorithm 
        ActionListener listener = new ButtonListener();
        stepButton.addActionListener(listener);

        buttonPanel.add(stepButton); 
        buttonPanel.add(runButton);
        panel.add(buttonPanel,BorderLayout.PAGE_START); //add the buttonPanel  at the top of the panel
        panel.add(arrayComp,BorderLayout.CENTER); //add the arraycoponent object in the center of teh panel
        frame.add(panel);
        frame.setVisible(true);         
        //print the entries in the array
        //System.out.println(arrayComp);

    }
}

数组组件:

import javax.swing.JComponent;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.Color;

public class ArrayComponent extends JComponent 
{
    private int[] theArray;
    final int dx=6; //the width of thebars (as well as the with of the spaces between bars)
    private int space=0;
    int index1 =0;
    int index2 =0;
    public ArrayComponent(int[] a)
    {
        theArray=a;    
        space=600-12*theArray.length/2; //space amount on the horizontal axes to center the graph                                      
        //600 is the frame width in the viewer program
        //For each bar 12 units on the horixzontal axis is used including the space following it.
        //something.addActionListener(new ButtonListener());
    }

    public void setIndices(int i, int j)
    {
        index1 = i;
        index2= j;
    }

    public void paintComponent(Graphics g)
    {        
        Graphics2D pen= (Graphics2D) g;
        for (int k=0;k<theArray.length;k++)
        {
            pen.drawRect(space+2*k*dx,5,dx,theArray[k]); 
            //space: initial space 
            //2*k*dx:  the (horizontal) distance of te kth bar from the start of the graph
            //5: bars are located on y=5
            //dx: the width of the bars
            //theArray[k]: height of the kth bar
        } 
        pen.fillRect(space+2*index1*dx,5,dx,theArray[index1]);
        pen.fillRect(space+2*index2*dx,5,dx,theArray[index2]);
    }

    public String toString()
    {
        String str=("array=[");
        int k=0;
        for (k=0;k<theArray.length-1;k++)
            str=str+theArray[k]+", ";              
        str=str+theArray[k]+"]";
        return str;
    }

}

ArrayUtil(创建随机数组):

import java.util.Random;

/**
   This class contains utility methods for array manipulation.
*/  
public class ArrayUtil
{ 
   private static Random generator = new Random();

   /**
      Creates an array filled with random values.
      @param length the length of the array
      @param n the number of possible random values
      @return an array filled with length numbers between
      0 and n - 1
   */
   public static int[] randomIntArray(int length, int n)
   {  
      int[] a = new int[length];      
      for (int i = 0; i < a.length; i++)
         a[i] = generator.nextInt(n);

      return a;
   }
}

对不起,如果帖子很长。该程序已经绘制了数组,它只是不对它们进行排序。感谢您的帮助。

【问题讨论】:

  • 你是什么意思“必须显示正在逐步排序的数组”?
  • 即使使用循环,您仍然可以显示正在逐步排序的数组。事实上,如果不使用循环,您就无法做到这一点(无论是排序还是逐步显示)。
  • 所以如果数组是 {5,4,3,2,1} 并且用户是 Step 按钮。它会像预期的那样切换 5 和 1,但我想停在那里并且不再排序,直到用户再次点击 step 按钮。
  • @Champ 更改您的问题以反映您刚才所说的内容
  • 将数组排序器用作线程(是的,使用普通循环)。它只会执行一个步骤,并且会阻塞,等待来自 GUI 线程的按钮单击,这将恢复线程以执行其下一次迭代。

标签: java arrays selection-sort


【解决方案1】:

activeIndex 引用下一个要排序的数组元素的索引(从值0开始)。

写一个方法,比如说stepSelectionSort,它只执行选择排序的一个步骤并返回。排序从 array[activeIndex] 开始。

{5,4,3,2,1} -> activeIndex=0 -> Step.click -> stepSelectionSort() 在 0 处对数组元素进行排序 -> {1,4,3,2,5} -> 绘制() -> activeIndix=1 -> Step.click -> stepSelectionSort() 对数组元素 1 进行排序。

【讨论】:

  • 这样就可以了。基本上你有一个循环,但你记得位置(类数据 - 实例成员而不是本地 int)并且每次只进行一次迭代(中断和返回);
【解决方案2】:
  • 临时编写代码以在循环内进行完全排序
  • 将循环中的所有代码放入方法中
  • 每次用户单击“步骤”GUI 按钮时,删除循环并调用一次方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2013-04-09
    • 2012-06-09
    • 2013-11-01
    • 2018-07-14
    • 2019-05-13
    • 2021-12-20
    相关资源
    最近更新 更多