dimanche 16 mai 2021

Time testing problem for sorting methods using random numbers and arrays

I have working code for sort methods with time analysis code in the end, but can't figure out where to put the random number or array generator code for the sort methods. I get errors each time I try, hopefully someone can show me how it looks when the random method is called instead of the default assign. 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.

public class InsertSort {
private int[] arr;
public InsertSort(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 = {9,1,8,2,7,3,6,4,5};
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 number generator

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