2
I have a college job where I should create some vectors with random numbers and then sort in some methods(Insertion,Bubble,merge,etc).
After sorting, I need to count the number of comparisons that each method has made. How can I do this count in each method?
This algorithm below is organizing 2 vectors, one with size 5, generating 5 random numbers and another with size 10, generating 10 random numbers. It is possible to count the total number of comparisons made?
My Insertionsort code currently works normally but the comparison count is incorrect:
package insertion;
import java.util.Random;
public class insertion {
public static void main(String a[]){
Random r = new Random();//util para chamar os números aletórios
int[] vet5 = new int[5];
int[] vet10 = new int[10];
//vet5 não ordenados
for (int i = 0; i < vet5.length; i++) {
vet5[i] = r.nextInt(5);
}
//vet10 não ordenados
for (int i = 0; i < vet10.length; i++) {
vet10[i] = r.nextInt(10);
}
//--------------------------------------------//
//vet5 ordenados
int[] arr2 = doInsertionSort(vet5);
int cont5 = 0;
System.out.println("\nVetores com 5 ordenados: ");
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
cont5++;
}
System.out.println("\nTotal de comparações com 5: "+cont5);
//vet10 ordenados
int[] arr3 = doInsertionSort(vet10);
int cont10 = 0;
System.out.println("\nVetores com 10 ordenados: ");
for(int i:arr3){
System.out.print(i);
System.out.print(", ");
cont10++;
}
System.out.println("\nTotal de comparações com 10: "+cont10);
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
}
You see this
if
in the static method? Just put onecomparacoes++
before him, beingstatic int comparacoes
an entire static variable; obviously, re-reset the comparison contactor before each round...– Jefferson Quesado
@Jeffersonquesado but this way it would be possible to have the number of comparisons of each vector (the 5 and 10)? 'Cause from what I understand it would only count to one
– ncesar
If you put it in the right corner, the increment will occur next to the comparison, then you will be doing it in the right corner. You will find that it is proportional to the square of the vector size
– Jefferson Quesado