没有循环的选择排序

时间:2013-04-20 17:59:49

标签: java arrays selection-sort

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

ArrayViewer:

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);

    }
}

ArrayComponent:

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;
   }
}

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

2 个答案:

答案 0 :(得分:1)

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

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

{5,4,3,2,1} - &gt; activeIndex = 0 - &gt; Step.click - &gt; stepSelectionSort()将数组元素排序为0 - &gt; {1,4,3,2,5} - &gt; draw() - &gt; activeIndix = 1 - &gt; Step.click - &gt; stepSelectionSort()对数组元素1进行排序。

答案 1 :(得分:0)

  • 暂时编写代码以在循环中进行完全排序
  • 获取循环中的所有代码并将其放入方法
  • 删除循环&amp;每次用户单击“步骤”GUI按钮
  • 时调用该方法一次