Question

For this program I want to implement an array of sorting and searching algorithms. The array will be filled with random numbers. Then I want to draw each array element as a bar (making something like a bar graph). I have a step and run button in the GUI the step is supposed to use selection sort. The problem I am having is: I only know how to do selection sort with a loop. However, I can not use a loop because I have to show the array being sorted step by step. Can anyone show me how to do selection sort without a loop? I will be adding all of the code I have so far because this is my first time posting anything, and I want to make sure I am specific.

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(creates the random array):

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

Sorry if the post is lengthy. The program already draws the arrays, it just does not sort them. Thanks for the help.

Était-ce utile?

La solution

Let activeIndex refer to the index of the array element to be sorted next (starting with value 0).

Write a method, say stepSelectionSort, which will execute only the one step of selection sort and return. The sorting begins at array[activeIndex].

{5,4,3,2,1} -> activeIndex=0 -> Step.click -> stepSelectionSort() sorts array element at 0 -> {1,4,3,2,5} -> draw() -> activeIndix=1 -> Step.click -> stepSelectionSort() sorts array element 1.

Autres conseils

  • Temporarily write code to do full sort inside a loop
  • Take all code within the loop and put it in a method
  • Remove the loop & call the method once each time the user clicks "Step" GUI button
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top