dimanche 30 mai 2021

Time testing code issues for sorting methods with random numbers [duplicate]

I have working code for sort methods with time analysis code in the end, but when I put my random number generator code in the method call instead of the default assign int[] list = {9,1,8,2,7,3,6,4,5}; I get an error - Type mismatch: cannot convert from ArrayList to int[]." I tried changing generateRandomList to return an array but still get same error, then I tried changing every "array" to "list" in the InsertSort class, and still get the same error in the timing code "Type mismatch: cannot convert from ArrayList to int[], then presuming I have to change from arraylist to list in the Random class, but then when I do so for the Random class I get the error "Cannot instantiate the type List". Hopefully someone can show me what I'm doing wrong and help me fix this. Also, is the timing part done right? It doesn't seem like it should take that long, when I run I get something like 69391841667800 nanoseconds.

Here is my code for InsertSort timing analysis (InsertTime) -

public class InsertTime {
private int[] arr;
public InsertTime(int[] array) {
arr = array;
}
private boolean more(int value1, int value2)
{
return value1 > value2;
}
public void sort()
{
int size = arr.length;
int temp,j;
for(int i=1; i<size; i++)
{temp=arr[i];
for(j=i; j>0 && more(arr[j-1], temp); j--)
{
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
public static void main(String[] args)
{
    int[] array = Random.generateRandomList(5, 1, 10);
InsertSort bs = new InsertSort(array);
bs.sort();
for(int i=0;i<array.length ;i++)
{
System.out.print(array[i] + " ");
}
long endTime = System.nanoTime(); //Current system Time at end

long startTime = 0;
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

System.out.print(duration);
}
}

This is my code for Random -

import java.util.ArrayList;

public class Random {

public static void main(String[] args)
{
    System.out.println(generateRandomList(5, 1, 10));
}

public static ArrayList<Integer> generateRandomList( int size, int min, int max) {
    ArrayList<Integer> list;
    list = new ArrayList<>();
    for(int i=0;i<size;i++) {
        int n = (int)(Math.random() * (max-min))+min;
        list.add(n);
    }
    return list;
}

}



Aucun commentaire:

Enregistrer un commentaire