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

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)...
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...
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,...
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...
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...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
Suppose we have a Java class called Person.java public class Person { private String name; private...
Suppose we have a Java class called Person.java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName(){return name;} public int getAge(){return age;} } (a) In the following main method which lines contain reflection calls? import java.lang.reflect.Field; public class TestPerson { public static void main(String args[]) throws Exception { Person person = new Person("Peter", 20); Field field = person.getClass().getDeclaredField("name"); field.setAccessible(true); field.set(person, "Paul"); } }...
public class CDLL_Node<T> { private T data; private CDLL_Node<T> prev, next; // EACH CDLL_Node PTS TO...
public class CDLL_Node<T> { private T data; private CDLL_Node<T> prev, next; // EACH CDLL_Node PTS TO ITS PREV & NEXT public CDLL_Node() { this( null, null, null ); // 3 FIELDS TO INIT } public CDLL_Node(T data) { this( data, null, null); } public CDLL_Node(T data, CDLL_Node<T> prev, CDLL_Node<T> next) { setData( data ); setPrev( prev ); setNext( next ); } public T getData() { return data; } public CDLL_Node<T> getPrev() { return prev; } public CDLL_Node<T> getNext() { return...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT