The goal of my code is to continuously print the first k elements of my array in ascending order and only stop once it has reached the time limit (int n) in seconds given by the user.
Method shuffleR (t == 6)
works fine for me (shuffling the first k elements) while insertionSort (t == 7)
is not generating the expected output even if the only thing I changed was the method. My problem is that the generated array is not being passed onto the insertionSort. Not sure what I did wrong so I'm asking here for some help. Thank you in advance!
Here is my shuffleR (t == 6) and insertionSort (t == 7) method:
public static int[] shuffleR(int [] arr, int n)
{
if (n <= 1) // if there is only one number, return n
{
return arr;
}
// swaps the nth element with the element in a randomly selected index
int index = (int)((n-2)*Math.random());
int temp = arr[n-1];
arr[n-1] = arr[index];
arr[index] = temp;
return shuffleR(arr, n-1);
}
public static int[] insertionSort(int [] arr)
{
int temp = 0;
for(int i = 0; i < arr.length; i++){
for(int j = i + 1; j < arr.length; j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
Here is the portion of my code in the main method which is supposed to print the output:
else if (t == 6 || t == 7)
{
// creates an array with 20000 elements
Random rd = new Random();
int[] arr = new int[20000];
for (int i = 0; i < arr.length; i++)
{
arr[i] = rd.nextInt(10000); // storing random integers in array 'arr'
}
if (t == 6) // shuffleR
{
startLoop = System.nanoTime();
System.out.println("\nShuffled numbers:"); // print shuffled numbers
while (elapsedTime < maxTime)
{
int[] result = shuffleR(arr, k); // call method shuffleR
System.out.println("k = " +k);
for(int i = 0; i < k; i++)
{
System.out.println("Index ["+ i +"] = "+ result[i]);
}
System.out.println(";");
currentTime = System.nanoTime();
elapsedTime = (currentTime - startLoop) / 1000000000;
k++;
}
System.out.println("\nLargest k: " + (k-1));
}
else if (t == 7) // insertionSort
{
startLoop = System.nanoTime();
System.out.println("\nSorted numbers:"); // print sorted numbers
while (elapsedTime < maxTime)
{
int [] result = insertionSort(arr); // call method insertionSort
System.out.println("k = " +k);
for(int i = 0; i < k; i++)
{
System.out.println("Index ["+ i +"] = "+ result[i]);
}
System.out.println(";");
currentTime = System.nanoTime();
elapsedTime = (currentTime - startLoop) / 1000000000;
k++;
}
System.out.println("\nLargest k: " + (k-1));
}
Expected Ouput:
k = 1
Index [0] = 933
;
k = 2
Index [0] = 933
Index [1] = 1001
;
k = 3
Index [0] = 153
Index [1] = 933
Index [2] = 1001
and so on...
My Output:
k = 1
Index [0] = 0
;
k = 2
Index [0] = 0
Index [1] = 0
;
k = 3
Index [0] = 1
Index [1] = 1
Index [2] = 1
;
and so on...
Aucun commentaire:
Enregistrer un commentaire