In: Computer Science
I need to write a method that sorts a provided Linked list with bubble sort and using ONLY Java List Iterator Methods (Link Below)
https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html
public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {
// first line to start you off
ListIterator<E> iit = c.listIterator(), jit;
/**** Test code: do not modify *****/
List cc = new LinkedList(c);
Collections.sort(c);
ListIterator it1 = c.listIterator(), it2 = cc.listIterator();
while (it1.hasNext()) {
if (!it1.next().equals(it2.next()))
throw new Exception("List not sorted");
}
/***********************************/
}
Here is the completed code for this method. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
//required method implementation
public static <E extends Comparable<? super E>> void bubbleSort(List<E> c)
throws Exception {
// first line to start you off
ListIterator<E> iit = c.listIterator(), jit;
int index = 0; // index of current element the iterator iit is iterating
// looping until list is fully sorted
while (iit.hasNext()) {
System.out.println(c);
// getting an iterator
jit = c.listIterator();
// declaring two E objects to null
E ob1 = null, ob2 = null;
// setting ob1 to first element
if (jit.hasNext()) {
ob1 = jit.next();
}
// loops as long as there is an element left to read
while (jit.hasNext()) {
ob2 = jit.next();
// comparing ob1 and ob2
if (ob1.compareTo(ob2) > 0) {
// ob1 and ob2 needs to be swapped
// this can be done by removing last two values iterated and
// adding in reverse order
jit.previous();
jit.previous(); // now the iterator cursor is at ob1
// removing ob1
jit.remove();
// moving to ob2
jit.next();
// removing ob2
jit.remove();
// adding ob2, and then ob1
jit.add(ob2);
jit.add(ob1);
// resetting iit so that ConcurrentModificationException is
// not thrown, starting iteration from index 'index'
iit = c.listIterator(index);
} else {
ob1 = ob2;
}
}
//calling next element in iit, updating index
iit.next();
index++;
}
/**** Test code: do not modify *****/
List cc = new LinkedList(c);
Collections.sort(c);
ListIterator it1 = c.listIterator(), it2 = cc.listIterator();
while (it1.hasNext()) {
if (!it1.next().equals(it2.next()))
throw new Exception("List not sorted");
}
}