Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Help I'm trying to calculate the average time of the sorted array and print it out, heres my code import java.util.*; public class test {

Help I'm trying to calculate the average time of the sorted array and print it out, heres my code

import java.util.*; public class test { public static void main(String[] args) { int[] arr1 = new int[100]; // array 1 = 100 random numbers // random number generator Random random = new Random(); for (int i = 0; i < 100; i++) { arr1[i] = random.nextInt(500); } System.out.println("Before Quick Sort: "); printArray(arr1); quickSortSub(arr1); System.out.println("After Quick Sort: "); printArray(arr1);

System.out.println(); System.out.println("Sorts " + "\t\t | \t" + "Time"); System.out.println("-----------------------------------------------------------------"); System.out.print("Quick:"); for(int i = 0; i < 10; i++) { quickTime(arr1); System.out.println(" -----------------------------------------------------------------"); } } private static void quickSort(int[] list, int first, int last){ if(last > first){ int pivotIndex = partition(list, first, last); quickSort(list, first, pivotIndex - 1); quickSort(list, pivotIndex + 1, last); } } //partition the array list[first.... last] private static int partition(int[] list, int first, int last){ int pivot = list[first]; // choose the first element as the pivot int low = first + 1; // Index for forward search int high = last; // index for backward search while(high > low){ //search forward from left while(low <= high && list[low] <= pivot) low++; //search backward from right while(low <= high && list[high] > pivot) high--; //swap two elements in list if(high > low){ int temp = list[high]; list[high] = list[low]; list[low] = temp; } } while(high > first && list[high] >= pivot) high--; // Swap pivot w/ list[high] if(pivot > list[high]){ list[first] = list[high]; list[high] = pivot; return high; } else{ return first; } } public static void quickSortSub(int[] list){ quickSort(list, 0, list.length - 1); } // a method for getting the time public static void quickTime(int[] list){ long startTime, stopTime, elaspedTime; int sum = 0; startTime = System.nanoTime(); quickSortSub(list); stopTime = System.nanoTime(); elaspedTime = stopTime - startTime; System.out.print(" \t\t | \t" + elaspedTime); } public static void printArray(int[] arr){ for(int a: arr){ System.out.print( " | " + a); } System.out.println(); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions