Question

In: Computer Science

Using this BubbleSort implementation in Java: public class BubbleSort<T extends Comparable<T>> {    private static <T...

Using this BubbleSort implementation in Java:

public class BubbleSort<T extends Comparable<T>>
{

   private static <T extends Comparable<T>>
   void swap(T[] data, int index1, int index2)
   {
      T temp = data[index1];
      data[index1] = data[index2];
      data[index2] = temp;
   }
   public void sort(T[] data)
   {
      int position, scan;

      for (position = data.length - 1; position >= 0; position--)
      {
         for (scan = 0; scan <= position - 1; scan++)
         {
            if (data[scan].compareTo(data[scan + 1]) > 0)
               swap(data, scan, scan + 1);
         }
      }
   }
}

Modify the code to reflect the following: If the inner loop completes without performing any exchanges, the array must already be sorted, so the sort can stop. Introduce a flag set to false before the inner loop starts, but which the inner loop sets true when it calls swap. Then have the outer loop stop when the inner loop completes without doing a swap.

Solutions

Expert Solution

Required solution is

Steps :-

1.) declare a variable flag of boolean type which is initialized as true.

boolean flag = true;

2.) in outer loop, add flag with loop condition with AND(&&)

for (position = data.length - 1; position >= 0 && flag ; position--)

3.) before start at the inner loop, set flag to false value

4.) while swapping occurred set the flag to true value


Explanation:

Complete program will be

BubbleSort.java

public class BubbleSort<T extends Comparable<T>>


{


        private static <T extends Comparable<T>>


                        void swap(T[] data, int index1, int index2)


        {


                T temp = data[index1];


                data[index1] = data[index2];


                data[index2] = temp;


        }


        public void sort(T[] data)


        {


                int position, scan;


                boolean flag = true;


                for (position = data.length - 1; position >= 0 && flag; position--)


                {
                        flag = false; // a flag set to false before the inner loop starts


                        for (scan = 0; scan <= position - 1; scan++)


                        {


                                if (data[scan].compareTo(data[scan + 1]) > 0) {


                                        swap(data, scan, scan + 1);
                                        flag = true; // inner loop sets true when it calls swap
                                }


                        }


                }


        }


}

Related Solutions

public class ProductThread { static class ProductThreads extends Thread{ private int begin, end; int[] v1, v2;...
public class ProductThread { static class ProductThreads extends Thread{ private int begin, end; int[] v1, v2; long ris; public ProductThreads(String name, int [] v1, int [] v2, int begin, int end) { setName(name); this.v1 = v1; this.v2 = v2; this.begin = begin; this.end = end; this.ris = 0; } public void run() { System.out.println("Thread " + Thread.currentThread().getName() + "[" + begin + "," + end + "] started"); ris = 1; for(int i = begin; i <= end; i++) ris...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement the compareTo method to compare the triangles on the basis of similarity. Draw the UML diagram for your classes. Write a Driver class (class which instantiates the comparableTriangle objects) to determine if two instances of ComparableTriangle objects are similar (sample output below). It should prompt the user to enter the 3 sides of each triangle and then display whether or not the are similar...
The following Java program is NOT designed using class/object concept. public class demo_Program4_non_OOP_design { public static...
The following Java program is NOT designed using class/object concept. public class demo_Program4_non_OOP_design { public static void main(String[] args) { String bottle1_label="Milk"; float bottle1_volume=250; float bottle1_capacity=500; bottle1_volume=addVolume(bottle1_label, bottle1_volume,bottle1_capacity,200); System.out.println("bottle label: " + bottle1_label + ", volume: " + bottle1_volume + ", capacity: " +bottle1_capacity); String bottle2_label="Water"; float bottle2_volume=100; float bottle2_capacity=250; bottle2_volume=addVolume(bottle2_label, bottle2_volume,bottle2_capacity,500); System.out.println("bottle label: " + bottle2_label + ", volume: " + bottle2_volume + ", capacity: " +bottle2_capacity); } public static float addVolume(String label, float bottleVolume, float capacity, float addVolume)...
Using maps in Java. Make a public class called ExampleOne that provides a single class (static)...
Using maps in Java. Make a public class called ExampleOne that provides a single class (static) method named firstOne. firstOne accepts a String array and returns a map from Strings to Integer. The map must count the number of passed Strings based on the FIRST letter. For example, with the String array {“banana”, “apples”, “blueberry”, “orange”}, the map should return {“b”:2, “a”:1, “o”:1}. Disregard empty Strings and zero counts. Retrieve first character of String as a char using charAt, or,...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome takes a Scanner scn as its parameter and returns a String. It returns the longest token from scn that is a palindrome (if one exists) or the empty string (otherwise). (Implementation note: You'll find your isPalindrome method helpful here. This method calls for an optimization loop.)
Write a java code for LinkedStack implementation and the code is: public final class LinkedStack<T> implements...
Write a java code for LinkedStack implementation and the code is: public final class LinkedStack<T> implements StackInterface<T> {    private Node topNode; // References the first node in the chain       public LinkedStack()    {        topNode = null;    } // end default constructor       public void push(T newEntry)    { topNode = new Node(newEntry, topNode); //       Node newNode = new Node(newEntry, topNode); //       topNode = newNode;    } // end push    public...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void main(String[] args) { Rectangle r1 = new Rectangle(0,0,100,150); System.out.println(r1);    Rectangle r2 = new Rectangle(50,75,100,150); System.out.println(r2);    Rectangle r3 = r1.intersection(r2);    } } Write a program that takes both Rectangle objects, and uses the intersection method to determine if they overlap. If they do overlap, then print it's coordinates along with its width and height. If there is no intersection, then have the...
Using Java The given class SetInterface.java is : public interface SetInterface<T> {    /**    *...
Using Java The given class SetInterface.java is : public interface SetInterface<T> {    /**    * Gets the current number of entries in this set.    *    * @return The integer number of entries currently in the set.    */    public int getSize();    /**    * Sees whether this set is empty.    *    * @return True if the set is empty, or false if not.    */    public boolean isEmpty();    /**    *...
Language: Java Topic: Deques Using the following variables/class: public class ArrayDeque<T> { /** * The initial...
Language: Java Topic: Deques Using the following variables/class: public class ArrayDeque<T> { /** * The initial capacity of the ArrayDeque. * * DO NOT MODIFY THIS VARIABLE. */ public static final int INITIAL_CAPACITY = 11; // Do not add new instance variables or modify existing ones. private T[] backingArray; private int front; private int size; Q1: write a method called "public void addLast(T data)" which adds an element to the back of a Deque. If sufficient space is not available...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare variables int hrsWrked; double ratePay, taxRate, grossPay, netPay=0; string lastName; // enter the employee's last name Console.Write("Enter the last name of the employee => "); lastName = Console.ReadLine(); // enter (and validate) the number of hours worked (positive number) do { Console.Write("Enter the number of hours worked (> 0) => "); hrsWrked = Convert.ToInt32(Console.ReadLine()); } while (hrsWrked < 0); // enter (and validate) the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT