Sort
import java.util.ArrayList;
// extends generic interface comparable<t>, defines compareTo
class TQueue<T extends Comparable<T>> {
private List<T> items;
// initializes the items variable to a new ArrayList
public TQueue() {
items = new ArrayList<>();
}
//adds elements
public void enqueue(T item) {
items.add(item);
}
public T dequeue() {
if (items.isEmpty()) {
return null;
}
return items.remove(0);
}
//bubblesort function that compares elements next to each other, if the first element is greater than the second, then swap
public void bubbleSort() {
int n = items.size();
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (items.get(j).compareTo(items.get(j+1)) > 0) { //use compareTo to compare 2 elements
T temp = items.get(j);
items.set(j, items.get(j+1));
items.set(j+1, temp);
}
}
}
}
public void insertionSort() {
int n = items.size();
for (int i = 1; i < n; i++) {
T key = items.get(i); // assigns element to key
int j = i - 1;
while (j >= 0 && items.get(j).compareTo(key) > 0) { //checks if j value is greater than key, if it is then the element at j is moved to the right
items.set(j+1, items.get(j));
j--; // goes back to continue comparing key
}
items.set(j+1, key); //puts key at correct spot, sets value of j+1 to value of key, puts key in correct position
}
}
@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for (T item : items) {
sb.append(item.toString());
sb.append(", ");
}
sb.setLength(sb.length() - 2);
sb.append("]");
return sb.toString();
}
}
public class TQueue {
public static void main(String[] args) {
// Generic T Queue
GenericTQueue<Integer> queue = new GenericTQueue<>();
queue.enqueue(3);
queue.enqueue(1);
queue.enqueue(4);
queue.enqueue(1);
queue.enqueue(5);
queue.enqueue(9);
queue.enqueue(2);
queue.enqueue(6);
queue.enqueue(5);
System.out.println("Before: " + queue.toString());
queue.bubbleSort();
System.out.println("Bubble Sorting");
System.out.println("After: " + queue.toString());
GenericTQueue<Integer> queue1 = new GenericTQueue<>();
queue1.enqueue(3);
queue1.enqueue(1);
queue1.enqueue(4);
queue1.enqueue(1);
queue1.enqueue(5);
queue1.enqueue(9);
queue1.enqueue(2);
queue1.enqueue(6);
queue1.enqueue(5);
System.out.println("Insertion Sorting");
queue1.insertionSort();
System.out.println("After sorting: " + queue1.toString());
}
}
TQueue.main(null);