View Full Version : Help counting the number of comparisons in sorting a list.

03-29-2012, 05:00 AM

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.

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


03-29-2012, 08:40 PM
You need to call the setText method for the bottomLabel in the actionPerformed method. It won't change by itself.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum