In: Computer Science
in java. using the following template as a method, public static void shellSort(int[] array) {
create a program that counts the number of comparisons and swaps of the sorting method does using
int array1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Best Case Test int array2[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; // Worst Case Test int array3[] = {10, 4, 8, 2, 6, 1, 9, 3, 7, 5}; // Average Case Test
and have the counsel print out the results.
public class Main
{
public static void main(String[] args) {
int array1[] = {1, 2, 3, 4, 5, 6,
7, 8, 9, 10}; //best case
int array2[] = {10, 9, 8, 7, 6, 5,
4, 3, 2, 1}; // Worst Case Test
int array3[] = {10, 4,
8, 2, 6, 1, 9, 3, 7, 5};//average case
int
i,j,swaps1=0,comparisons1=0,len1,temp,swaps2=0,comparisons2=0,len2,len,swaps3=0,comparisons3=0,len3;
//System.out.println("In Best
case :\n1.swaps:"+swaps1+"2.comparisons :"+comparisons1);
len1=array1.length;
swaps1=0;
temp=array1[0];
for(i=0;i<len1;i++)
{
for(j=i+1;j<len1;j++)
{comparisons1=comparisons1+1;
if(array1[i]>array1[j])
{
temp=array1[i];
array1[i]=array1[j];
array1[j]=temp;
swaps1=swaps1+1;
}
}
}
System.out.println("In Best
case :\n1.swaps:"+swaps1+"\n2.comparisons :"+comparisons1);
len2=array2.length;
swaps2=0;
for(i=0;i<len2;i++)
{
for(j=i+1;j<len2;j++)
{comparisons2=comparisons2+1;
if(array2[i]>array2[j])
{
temp=array2[i];
array2[i]=array2[j];
array2[j]=temp;
swaps2=swaps2+1;
}
}
}
System.out.println("In Worst
case :\n1.swaps:"+swaps2+"\n2.comparisons :"+comparisons2);
len3=array3.length;
swaps3=0;
comparisons3=0;
for(i=0;i<len3;i++)
{
for(j=i+1;j<len3;j++)
{comparisons3=comparisons3+1;
if(array3[i]>array3[j])
{
temp=array3[i];
array3[i]=array3[j];
array3[j]=temp;
swaps3=swaps3+1;
}
}
}
System.out.println("In
Average case :\n1.swaps:"+swaps3+"\n2.comparisons
:"+comparisons3);
}
}
output:
If you have any queries...please comment...Thank you...