I am currently working on a project where I need to create an initial array (anArray) with randomly generated integers and make an exact copy of those random values in another array (arrayB). I then want to sort the first array with my selectionSort() method, and the second array with Arrays.sort(). I also need to time how long each sorting method takes to complete.
So far, I can populate the first array with random integers. I'm not sure if I have correctly copied the anArray into arrayB because it's not printing as I have coded so far. anArray is sorting as required, and printing through main with no problems. Please check out my code so far and if you can advise on where to add the way to time the sorting processes that would be awesome too!
import java.util.Arrays;
import java.util.Random;
public class TimedSortOne
{
public static int[] anArray; // initializes the first array
public static int[] arrayB; // initializes the second array
/**
* This method produces integers of random values.
* @return int randomNum
*/
private static int randomFill()
{
Random rand = new Random();
int randomNum = rand.nextInt();
return randomNum;
}
private static int[] list()
{
anArray = new int[1000];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray;
}
/**
* This method sorts the values of anArray into ascending order by
* repeatedly finding the largest value and moving
* it to the last index in the array.
* @param int[] anArray
*/
private static void selectionSort(int[] anArray)
{
for (int lastPlace = anArray.length-1; lastPlace > 0; lastPlace--)
{
int maxLoc = 0;
for (int j = 1; j <= lastPlace; j++)
{
if (anArray[j] > anArray[maxLoc])
{
maxLoc = j;
}
}
int temp = anArray[maxLoc];
anArray[maxLoc] = anArray[lastPlace];
anArray[lastPlace] = temp;
}
}
/**
* This method populates arrayB with an exact copy
* of integer values from anArray using System.arraycopy() function.
* @param anArray
* @return arrayB
*/
private static int[] arrayCopyFull(int[] anArray)
{
int[] temp = new int[anArray.length];
System.arraycopy(anArray, 0, temp, 0, anArray.length);
return temp;
}
public static void main(String[] args)
{
list();
arrayCopyFull(anArray);
selectionSort(anArray);
System.out.println("The sorted integers in anArray are:");
for (int numbers : anArray) {
System.out.println(numbers);
}
System.out.println("The sorted integers in arrayB are:");
for (int bNumbers : arrayB) {
System.out.println(bNumbers);
}
}
}
So, I'm expecting to produce a printed list of anArray, sorted, with a record of the time it took to sort anArray.
And then, using arrayB as an exact copy of the random integers in anArray, sort arrayB with Arrays.sort() all with a record of the sorting time.