Question: in JAVA : Create an array of rectangles using the file provided. Modify the bubble sort algorithm to work with ANY object. Print out the

in JAVA : Create an array of rectangles using the file provided. Modify the bubble sort algorithm to work with ANY object.

Print out the original unsorted array of rectangles and then print out the sorted array of rectangles through each step or swap.

Please use a method to print the arrays.

input file: 4.7 2.9 4.9 1.0 3.5 3.3 1.1 5.5 4.2 1.9 8.3 3.6 7.5 2.0 4.4 3.3 6.1 2.2 2.1 1.0

What I have so far:

//move higher valued elements to the right, lower to the left public static > void bubbleSort(T[] theArray, int n) { boolean sorted = false; // false when swaps occur //loop through the entire array AND as long as sorted is FALSE for (int pass = 1; (pass < n) && !sorted; ++pass) { sorted = true; // assume sorted for (int index = 0; index < n - pass; ++index) { int nextIndex = index + 1; if (theArray[index].compareTo(theArray[nextIndex]) > 0) //if the pair is out of orderexchange items { T temp = theArray[index]; // exchange items theArray[index] = theArray[nextIndex]; theArray[nextIndex] = temp; sorted = false; // signal exchange } // end if } // end for } // end for } // end bubbleSort

public static void main(String[] args) { // read file circles.in File inFile = new File("rectangles.in");

Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { } int n=0; //input into array double[] rectangles = new double[15]; while (fileInput.hasNext()) { if (fileInput.hasNextDouble()) { rectangles[n]=(fileInput.nextDouble()); n++; } else fileInput.next(); } //print arrays print(rectangles,n); }

public static void print(double [] rectangles, int n){ //print unsorted array System.out.println("Before Sorting: "+Arrays.toString(rectangles)); double[] num = new double[rectangles.length]; for (int i = 0; i < rectangles.length; i++) { num[i] = rectangles[i]; } //print sorted array bubbleSort(num, num.length); System.out.print("After SOrting: ["); for (int i = 0; i < rectangles.length; i++) { System.out.print(num[i] + ", "); } System.out.print("]"); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!