vee
vee

Reputation: 17

use same random array for each sort

I'm trying to make it so i generate a random array but implement just that one same array(in the random order) with different sorts. I have:

public static void main(String[] args)
{
    int[] array = new int[10];
    for(int i = 0; i < array.length; i++) {
        array[i] = (int)(Math.random()*100);}

    System.out.println("\nBefore Bubble Sort: ");
    for (int element : array)
        System.out.print(element + "  "); 

    bubbleSort(array);


    System.out.println("After Bubble Sort: "); 
    for (int element : array)
        System.out.print(element + "  ");
    System.out.println("\n");

    System.out.println("\nBefore Insertion Sort: ");
    for (int element : array)
        System.out.print(element + "  "); 

    insertionSort(array);


    System.out.println("After Insertion Sort: "); 
    for (int element : array)
        System.out.print(element + "  ");
    System.out.println("\n");
}

With corresponding code for the sorts (I will post them if necessary). Its output is:

Array Before Bubble Sort: 
2 64 27 1 81 60 72 6 9 82
Array After Bubble Sort: 
1 2 6 9 27 60 64 72 81 82 

Array Before Insertion Sort: 
1 2 6 9 27 60 64 72 81 82 
Array After Insertion Sort: 
1 2 6 9 27 60 64 72 81 82 

I want this array 2 64 27 1 81 60 72 6 9 82 to be in the before insertion line as well. The sorted array from bubble sort is just being put in the insertion sort so it's not doing anything. I think I need to make a method for the random array and call that with each sort? How would I do that? Or any other solution I'd appreciate. I will edit with more information if needed.

Upvotes: 1

Views: 64

Answers (2)

alseether
alseether

Reputation: 1993

You should make a copy of initial array in order to maintain the same data as original.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

Clone or copy the array before each sort and pass the clone to the sort routine. You can use array.clone() or Arrays.copyOf(array, array.length) to make the copy.

public static void main(String[] args)
{
 int[] array = new int[10];
  for(int i = 0; i < array.length; i++) {
   array[i] = (int)(Math.random()*100);}

   System.out.println("\nBefore Bubble Sort: ");
    for (int element : array)
      System.out.print(element + "  "); 

   int[] sorted = array.clone();
   bubbleSort(sorted);


   System.out.println("After Bubble Sort: "); 
    for (int element : sorted)
      System.out.print(element + "  ");
      System.out.println("\n");

   System.out.println("\nBefore Insertion Sort: ");
    for (int element : array)
        System.out.print(element + "  "); 

    sorted = array.clone();
    insertionSort(sorted);


    System.out.println("After Insertion Sort: "); 
    for (int element : sorted)
        System.out.print(element + "  ");
    System.out.println("\n");
}

Upvotes: 2

Related Questions