I have created a BubbleSort class in Java. I would like to test that class with
ID: 3832242 • Letter: I
Question
I have created a BubbleSort class in Java. I would like to test that class with an array in a class called TestSort. How do I call the BubbleSort class to sort the array in the new class?
-----------------------------------------------------
import java.util.*;
public class BubbleSort
{
static void bubbleSort(int[] arr)
{
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
---------------------------------------------------------------------
import java.util.*;
public class TestSort
{
public static void main(String[] args)
{
int[] anArray ={26,45,67,89,23,47,32,98};
BubbleSort bs = new BubbleSort();
int[] newArray = bs.bubbleSort(anArray);
}
}
Explanation / Answer
bubbleSort() method in BubbleSort class is a static method. You should call these methods using the class name not using an object of the class. Also the bubbleSort() method doesn't return anything , it makes modifications to the same array that is passed to it.
So your TestSort class should look like this :
import java.util.*;
public class TestSort
{
public static void main(String[] args)
{
int[] anArray ={26,45,67,89,23,47,32,98};
BubbleSort.bubbleSort(anArray);
// I have added code to print the array after sorting.
for(int i=0; i< anArray.length; i++){
System.out.print(anArray[i] + " ");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.