Docsity

Java Array Selection Sort p, Assignments of Java Programming

Toggle sidebar
bg1
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());
pf2

Partial preview of the text

Download Java Array Selection Sort p and more Assignments Java Programming in PDF only on Docsity!

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"); } }