Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Help counting the number of comparisons in sorting a list.

1. ## Help counting the number of comparisons in sorting a list.

Hello,

My program needs to generate a list of random integers, the size being entered by the user. Then it needs to sort the list using the Selection Sort algorithm, keeping track of the comparisons made.

I think I have done well so far but for some reason the number of comparisons required are not printing to the screen.

Code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.*;

public class Comparisons extends JApplet implements ActionListener
{
private JTextField inputField;
private JButton button;
private JLabel topLabel, bottomLabel;
int values;
// Event handler method
public void actionPerformed(ActionEvent event)
{

int size;
// Allows input of list size
size = Integer.parseInt(inputField.getText());
values = process(size);
}

// Method calculates the number of comparisons needed to sort the list
// of numbers.
public int process(int size)
{
// Creates list of random integers
int value;
int numComparisons = 0;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random randomiser = new Random();

for (int count = 1; count <= size; count++)
{
value = Math.abs(randomiser.nextInt(size));
}

// Arranges list items in ascending order
for (int i = 0; i < size; i++)
{
// Find the index of the smallest component
for (int j = i + 1; j < size; j++)
{
numComparisons++;
// if j is less than i swap them
if (list.get(j) < list.get(i))
{
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
}
return numComparisons;
}

public void init()
{
setLayout(new GridLayout(4, 0));
inputField = new JTextField("Enter a number here");
button = new JButton("Enter");
topLabel = new JLabel("Enter a list size and press enter");
bottomLabel = new JLabel("Number of comparisons needed to sort the list: " + values);

}
}

• You need to call the setText method for the bottomLabel in the actionPerformed method. It won't change by itself.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•