

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The same task can take vastly different amounts of time, depending on the algorithm that is used to perform the task. You are familiar with simple sorting algorithms such as insertion sort and selection sort. (See Section 7.4 in the textbook.) While these methods work fine for small arrays, for larger arrays they can take an unreasonable amount of time. The question is whether we can do any better. Java has some built-in sorting methods. They can be found in the class named Arrays in the packag
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!


import java.util.Arrays; public class testSort { final static int SIZE = 1000; // length of array // Sort an array of real numbers using the selection sort algorithm. private static void selectionSort(int[] numbers) { for (int top = numbers.length-1; top > 0; top-- ) { int maxloc = 0; for (int i = 1; i <= top; i++) { if (numbers[i] > numbers[maxloc]) maxloc = i; } int temp = numbers[top]; } } public static void main(String[] args) { long startTime; // time when a sort begin. long endTime; // time when a sort ends. int[] numberList1; // An array of random numbers. int[] numberList2; // A copy of numberList1. numberList1 = new int[SIZE]; numberList2 = new int[SIZE]; //Fill the arrays with random integers. for(int i = 0; i < numberList1.length; i++) { numberList1[i] = (int) (Integer.MAX_VALUE * Math.random());
//The arrays have identical contents, with the same random numbers in both arrays. numberList2[i] = numberList1[i]; } // Time the selectionSort process startTime = System.nanoTime(); selectionSort(numberList1); endTime = System.nanoTime(); System.out.println("The time taken by selectionSort is: " + (endTime - startTime)+ " nano sec"); //Time the selectionSort process startTime = System.nanoTime(); Arrays.sort(numberList2); endTime = System.nanoTime(); System.out.println("The time taken by Arrays.sort is: " + (endTime - startTime)+ " nano sec"); } }