I have a college job where I have to 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 each method made. How can I make this count in each method?
This algorithm below is organizing 2 vectors, one with size 5, generating 5 random numbers and one with size 10, generating 10 random numbers. Is it possible to count the total number of comparisons made?
My InsertionSort code currently works normally but the compare 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;
}
}