Question: Modify code to count the number of swaps and comparisons import java.util.Random; public class QuickSort { private int[] data; private static Random generator = new

Modify code to count the number of swaps and comparisons import java.util.Random;

public class QuickSort { private int[] data; private static Random generator = new Random();

public QuickSort( int size ) { data = new int[ size ]; // create space for array

for ( int i = 0; i < size; i++ ) data[ i ] = 10 + generator.nextInt( 90 ); }

// call this method from the main program public void sort() { quickSortHelper( 0, data.length - 1 ); }

private void quickSortHelper( int left, int right ) { int pivot = partition( left, right );

if ( left < pivot - 1 ) quickSortHelper( left, pivot - 1 );

if ( pivot + 1 < right ) quickSortHelper( pivot + 1, right ); }

private int partition( int left, int right ) { int pivot = left;

while ( true ) { while ( data[ right ] >= data[ pivot ] ) { if ( right == pivot ) return pivot;

--right; }

swap( pivot, right );

pivot = right--;

while ( data[ left ] <= data[ pivot ] ) { if ( left == pivot ) return pivot;

++left; }

swap( pivot, left ); pivot = left++; } }

private void swap( int first, int second ) { int temporary = data[ first ]; data[ first ] = data[ second ]; data[ second ] = temporary; } }

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!