Attaching file and of question from HW and pasting my solution here. Giving erro
ID: 672770 • Letter: A
Question
Attaching file and of question from HW and pasting my solution here. Giving error Also attaching in pic. Pls guide me:
public class BulgarianSorter
{
public static void sort(int[] a)
{
while(!isSorted(a))
{
for (int i = 0; i< a.length; i=i+2)
sortThree(a, i);
}
}
/**
Sorts the three elements a[start], a[start + 1], a[start + 2].
If start > a.length - 3, sorts the one or two remaining elements.
*/
public static void sortThree(int[] a, int start)
{
int pos = start % 3;
if (pos == 1) {
/*
* two elements
*/
if (a[start] > a[start+1]) {
swap(a, start, start+1);
}
} else if (pos == 2) {
/*
* one remaining element - nothing to swap
*/
} else {
if (a[start] > a[start+1]) {
swap(a, start, start+1);
}
if (a[start+1] > a[start+2]) {
swap(a, start+1, start+2);
}
if (a[start] > a[start+1]) {
swap(a, start, start+1);
}
}
}
/**
Checks whether the given array is sorted.
@param a an array
@return true if the array is sorted
*/
public static boolean isSorted(int[] a)
{
int flag = 0;
for( int i = 0; i < a.length-1; i++)
{
if(a[i]>a[i+1]) {
flag = 0;
break;
}else{
flag = 1;
}
}
if(flag == 0){
return false;
}else return true;
}
/**
Swaps two entries of the array.
@param a an array
@param i the first position to swap
@param j the second position to swap
*/
private static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
The Bulgarian sort method relies on the fact that it's easy to sort an array of length 3. If ato and a1 are out of order, swap them. If a and a[ 21 are out of order, swap them. One more compare-and-swap (that you get to figure out), and you are done Implement the following algorithm: While the array is not sorted For each adjacent triple of elements starting at 0, 2, 4, 6, Sort the triple Submit a file BulgarianSorter.java. In the draft, just implement the sortTriple method. Use the following file: BulgarianSortTest.java mport java.util.*; import org.junit.*; mport static org.junit.Assert.*; public class BulgarianSortTest Test public void testsort3) int nums1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1 for (int i - 0; i , nums)Explanation / Answer
Visibly, the only problem with your code is here:
while(!isSorted(a))
{
for (int i = 0; i< a.length; i=i+2)
sortThree(a, i);
}
You are trying to sort every three elements in the list. In this case, the increment factor should be 3 and not 2. Show it should be re-written as:
while(!isSorted(a))
{
for (int i = 0; i< a.length; i=i+3)
sortThree(a, i);
}
Other than that, there is no notable errors in this logic.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.