Question: Code the Bubble Sort in a static method whose parameter is an array of integers to be sorted. Provide a driver program to demonstrate that
Code the Bubble Sort in a static method whose parameter is an array of integers to be sorted. Provide a driver program to demonstrate that the method functions properly. Modify the method described in the above exercise so that it counts and outputs the number of comparisons and swaps performed during each pass through the algorithm.
This a Bubble Sort that counts and outputs the number of comparisons and swaps performed during each pass through the algorithm. Be sure to provide the total number of comparisons and passes for the data set also. You should use the RandomIntegers class provided in the attachment to generate your data sets, There is a TestSort class that you should modify also to use the sort that you coded instead of the Arrays.sort method included there. Instead of a Bubble Sort you can choose to code one of the following sorts that also uses comparisons and swaps: Selection Sort, Insertion Sort, Shell Sort
import java.util.*;
/**
* The RandomInteger class generates an array of random integers of a specified size
* Duplicate integers are possible.
*
* @version NOvember 28, 2016
*/
public class RandomIntegers
{
private Random randomInteger;
private int testArray[];
/**
* Constructor for the RandomIntegers class
*
* @param n Integer that provides the size of the testArray
* @param bound Integer that provides the upper bound (exclusive) of the range
*/
public RandomIntegers(int n, int bound)
{
long seed = System.currentTimeMillis(); //Get current time as a long.
randomInteger = new Random(seed);//Use seed to generate random numbers.
testArray = new int[n];
for(int i = 0; i < n; i++)
testArray[i] = randomInteger.nextInt(bound);
}
/**
* Method to return the test array of integers.
*/
public int[] getTestArray()
{
return testArray;
}
}
import java.util.*;
/**
* Write a description of class TestSort here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TestSort
{
public static void main(String args[])
{
//Create test array
int[] test = new int[20];
RandomIntegers rtest = new RandomIntegers(20, 100); // Generate 20 in the 0 to 100 range
test = rtest.getTestArray(); //get those integers
//Print it out
System.out.println("Unsorted integers: ");
printArray(test);
//Sort it - Students replace this with your sort (bubble, merge, or quick)
Arrays.sort(test);
//Print sorted array
System.out.println(" Sorted integers: ");
printArray(test);
}
public static void printArray(int a[])
{
for (int i = 0; i< a.length ; i++)
{
if(i % 5 == 0)
System.out.println( ); //keep it 5 to a line
System.out.print(a[i] + " ");
}
System.out.println();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
