在这个程序中,我正在使用插入排序找到随机数组的排序数组。所以我现在遇到的问题是,在这个程序中,我还需要找到进行的比较次数以及在这个程序中进行的分配次数。我尝试了很多方法来查找比较和分配。我想我已经比较了,但是当我输出比较和分配时,它们应该彼此非常接近。当我输出它时,在我的程序中,它在某些情况下或全部情况下并不完全等于 well。我能做些什么?我不认为我正在使用冒泡排序,除非我......我将不得不从头开始。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package insertionsort;
import java.util.*;
/**
*
* @author Owner
*/
public class InsertionSort
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int randomInt;
int min;
int max;
int [] array;
int random=0;
int assign;
int temp;
int comparison=0;
int assignment=0;
int length;
int a;
int k;
System.out.print("How many random integers? ");
randomInt=input.nextInt();
System.out.print("Enter the minimum: ");
min=input.nextInt();
System.out.print("Enter the maximum: ");
max=input.nextInt();
array=new int [randomInt];
for (a=0; a<randomInt; a++)
{
assign=random;
random=(int)((Math.random()*(max-min+1)))+min;
array[a]=random;
}
System.out.println();
System.out.print("The randomized array is ");
for(int dot=0; dot<randomInt;dot++)
{
if (dot==randomInt-1)
System.out.printf("%d.", array[dot]);
else
System.out.printf("%d, ",array[dot]);
}
System.out.println();
length=array.length;
for (a=1;a<length; a++)
{
for (int b=0; b<a;b++)
{
comparison++;
if(array[b]>array[a])
{
temp=array[b];
array[b]=array[a];
for (k=a;k>b;k--)
{
array[k]=array[k-1];
assignment++;
}
array[b+1]=temp;
assignment++;
}
}
}
System.out.print("The sorted array is ");
for (a=0;a<length; a++)
{
if (a==length-1)
System.out.printf("%d.",array[a]);
else
System.out.printf("%d, ",array[a]);
}
System.out.println();
System.out.println("Total comparison count during sorting is " +comparison+ ".");
System.out.println("Total assignment count during sorting is " +(assignment)+ ".");
}
}