Programming Sorting Algorithms:
a. Describe an approach to modifying the Sorts.java program so that after calling a sorting method the program prints out the number of swaps needed by the sorting method.
b. Implement your approach.
c. Test your new program by running the selectionSort method.
Your program should report 49 swaps.
d. Now, modify your program to also output the number of comparisons (compares) needed.
You must include one or more statements to increment your counter within the sorting methods themselves.
For each of the listed methods, make and test the changes needed, and list both the number of swaps and the number of compares needed by the Sorts program to sort an array of 50 random integers.
selectionSort swaps:____
compares:____
bubbleSort swaps:____
compares:____
shortBubble swaps:____
compares:____
insertionSort swaps:____
compares:____
//---------------------------------------------------------------------------- //Sorts.java //
// Test harness used to run sorting algorithms.
//---------------------------------------------------------------------------- import java.util.*; import java.text.DecimalFormat; public class Sorts
{
static final int SIZE = 50;
// size of array to be sorted static int[] values = new int[SIZE];
// values to be sorted static void initValues()
// Initializes the values array with random integers from 0 to 99.
{ Random rand = new Random(); for (int index = 0; index < SIZE; index++) values[index] = Math.abs(rand.nextInt()) % 100; }
static public boolean isSorted() // Returns true if the array values are sorted and false otherwise.
{ boolean sorted = true; for (int index = 0; index < (SIZE - 1); index++) if (values[index] > values[index + 1]) sorted = false; return sorted; }