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);
System.out.println
("Number of Comparisons was " + totalWork);
System.exit(0);
}
// 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");
}
System.out.println();
}
}


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

Dani AI

Generated

A direct, minimal fix is to use the standard bubble-sort optimization: shrink the inner-loop limit each pass so later passes skip elements already bubbled to their final place. Add a boolean swapped to bail out early if no swaps occur. That meets 's suggestion to use a string array, avoids any index array, and addresses 's observation that a full inner loop causes extra comparisons.

import java.util.Scanner;

public class SortFourWords {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] words = new String[4];
        System.out.println("Enter four 3-letter words (space or newline separated):");
        for (int i = 0; i < 4; i++) words[i] = sc.next();
        System.out.print("Initially: ");
        for (String w : words) System.out.print(w + " ");
        System.out.println();

        int comparisons = 0;
        for (int pass = 0; pass < words.length - 1; pass++) {
            boolean swapped = false;
            for (int j = 0; j < words.length - pass - 1; j++) {
                comparisons++;
                if (words[j].compareTo(words[j + 1]) < 0) { // swap for descending order
                    String tmp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) break;
        }

        System.out.print("Sorted: ");
        for (String w : words) System.out.print(w + " ");
        System.out.println();
        System.out.println("Number of comparisons was " + comparisons);
    }
}

Notes and quick tips: the sample output is descending; change the compare sign for ascending. compareTo is case-sensitive — use compareToIgnoreCase() or toLowerCase() for case-insensitive sorting. If strict three-letter input is required, validate word.length() and reprompt. The swapped early-exit only reduces average comparisons; worst-case remains the reduced inner-loop total, and no index array is needed.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.