0

I have an arraylist containing 10 000 random values, ranging from 1-1000. I want to test various sorts (bubble, insertion, selection, etc) for their speed, and in order to do so fairly, I need to use the same array.

I create the array:

    int num;
    int[] data = new  int [10000]; 
    for (int i = 0; i < 10000; i++) {
    num=(int)(Math.random()*1000+1);
    data [i] = num;

I sort it using bubble sort:

{
            int tempVarBS;
    for (int i = 0; i < data.length-1; i++)
    {
       for(int j = 0; j < data.length-i-1; j++)
       {
                if(data[j] > data[j + 1])
                {
                       tempVarBS = data [j + 1];
                       data [j + 1]= data [j];
                       data [j] = tempVarBS;
                }
       }
    }
    for (int i = 0; i < data.length; i++)
    {
         System.out.println(data[i]);   
    }
}

Now, the array has been sorted. When I go to test the insertion sort, the array has already been sorted. For a small number of tests, I figured I could simply copy the array x number of times for x number of sorts I want to test.

However, that would be horribly inefficient for a large number of tests, so is there a way for me to only instantiate a single array, then sort it multiple times?

Essentially, I want to sort the array, but preserve the original unsorted array and reuse it each time I sort.

  • [Here](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) is a simple and powerful shuffling algorithm. – jrook Nov 09 '17 at 03:14
  • 1
    Remember, "reset/reshuffle" an array takes time too. And it might be slower than simply copying the array. – xiaofeng.li Nov 09 '17 at 03:18
  • I don't want to shuffle the data, I want to revert it to it's position before it was sorted. – Shivam Pandey Nov 09 '17 at 03:19
  • 1
    Read @xiaofeng.li 's comment. *Reverting* an array will possibly need more work and is more inefficient than keeping copies of the original array. It is not *horribly* inefficient. In fact it is the most efficient thing possible with the criteria you have given. If you are worried about memory, save the array to a file or something. – jrook Nov 09 '17 at 04:49
  • 1
    Do `copyArray = Arrays.copyOf(data, data.length)` before each type of sorting and sort `copyArray` so that `data` array always contains your original values in original order. – NAK Nov 09 '17 at 09:54

0 Answers0