Hi all,

This program below sorts arrays of integers.
It counts the number of times it compares pieces of
data to do the sort.With the array size set at 4 it always
takes 9 comparisons.

Does neone know how i can Modify it to read in a series of four 3-letter words and print them out in sorted
order. The program needs to keep a count of the number of string comparisons performed and never
take more than 6 comparisons to do the sort.
i was told that it can be done by altering the inner loop so that each
pass is shorter than the previous one. Problem is i cant seem to get it,
and it cant use an index array.

For example, if the user typed the following:
ant cat pan tap
The program should print out:
Initially: ant cat pan tap
Sorted: tap pan cat ant
Number of comparisons was 6

import javax.swing.*;
import java.util.*;
public class SearchPractice{
public static void main (String [] args)
final int SIZE = 4;
int numbers[] = new int;
int totalWork =0; //keep count of operations done
fill_array (numbers, SIZE);
System.out.print("Initially: ");
print_array (numbers, SIZE);
totalWork = bubble_sort (numbers, SIZE);
System.out.print("Sorted: ");
print_array (numbers, SIZE);
("Number of Comparisons was " + totalWork);
// Sort an array of integers using (an inefficient) variant of
// bubblesort
public static int bubble_sort (int array[], int arraySize)
int workDone = 0;
for (int pass = 0; pass < arraySize - 1; pass++)
for(int counter = 0; counter < arraySize - 1; counter++)
workDone = workDone + 1;
if (array[counter] > array[counter+1])
swap (array, counter, counter+1);
return workDone;
// Exchange a given pair of values given by their positions
// in an array
public static void swap (int a [], int p1, int p2)
int temp;
temp = a[p1];
a[p1] = a[p2];
a[p2] = temp;
// Fill an array from the keyboard
public static void fill_array (int array[], int arraySize)
for(int counter = 0; counter < arraySize; counter++)
array[counter] = Integer.parseInt
(JOptionPane.showInputDialog (
"Number for position:"+ counter));
// Print the contents of an array to the screen
public static void print_array (int array [], int arraySize)
for(int counter= 0; counter < arraySize; counter++)
System.out.print(array[counter] + "\t");

if neone knows neway to do this please let me know,,any help would be apreciated..

Hi everyone,

Throw your string datas into a string array and compare them in a loop. The number of comparisons is the final value of loop(if a break is required or not)

Richard West

This article has been dead for over six months. Start a new discussion instead.