Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Que#2 Sorts the elements of the list t so that the elements are in ascending ord

ID: 3877417 • Letter: Q

Question

Que#2 Sorts the elements of the list t so that the elements are in ascending order. A precondition of this method is that t must be already sorted in ascending order except that adjacent pairs of elements in t may be out of order. Consider the following almost sorted lists: 1, 0 is out of order 2, 1 is out of order 2, 1 is out of order 2, 1 and 4, 3 are out of order 3, 2 is out of order * [0, 2, 1, ] s s This method switches the positions of the out-of-order adjacent elements repairing the list so that it is in sorted order. para t thus a list of almost sorted elements * Opre. is sorted in ascending order except that adjacent pairs of elements may be out of order public static void repair(List t) { // if the list has less than 2 elements then is already sorted it (tasize()

Explanation / Answer

public static void repair(List<Integer> t){
if(t.size() < 2)
return ;
boolean flag = true;
boolean flag1 = false;
for(int i=0; i <t.size()-1; ++i ) {

if(t.get(i) > t.get(i+1)) {

if(flag) {
  System.out.println(i +" , " + (i+1));
flag = false;
}else{
  flag1 = true;
System.out.println(" and " + i +" , " + (i+1));
}
}
}
if(flag1)
System.out.println(" are out of order");
else
System.out.println(" is out of order");

}