Bubble Sort (Numbers Arrays)
Credit: Iterative Algorithms 1
Eventually, your goal will be to familiarize yourself with the following sort algorithms
Part 1 - Altering and Using the Code
Part 2 - Think about the following: (Not For Marks)
The question is, how to do you Bubble Sort an object? The algorithm works the same but you must decide what to sort by and build a specific method for that type of sort. Eg. For a Student class, you need a ‘Sort By Name’ and a ‘Sort by ID’.
The other wrinkle is that more often than not, when using OOP, you use ArrayLists rather than Arrays. ArrayList algorithms are sometimes shorter different than array algorithms as you can insert and delete items. Find a Bubble Sort algorithm that sorts an ArrayList and just look for differences.
Appendix A
Set Up for Students Doing these Assignments on their own time.
We will start with the bubble sort algorithm. Begin by watching this visualization of many different algorithms: https://www.youtube.com/watch?v=kPRA0W1kECg
Open your SearchAndSort.java file and add a comment section such as the following:
/***************************** Sort Algorithms *******************************************/.
//Bubble Sort
Read about Bubble Sort, watch a video and read a fun story using the algorithm:
The explanation: http://mathbits.com/MathBits/Java/arrays/Bubble.htm
The video is: Bubble Sort - http://www.youtube.com/watch?v=P00xJgWzz2c
The story is: Bullies, Bubble Sort and Soccer Tickets
Appendix B - Bubble Sort Start Code
Note that this sorts integer arrays from LARGEST to smallest. The assignments require you to reverse the sort.
public static void bubbleSort(int[] array){
boolean swap = true;
while (swap){
swap = false;
for (int i = 0; i < array.length-1; i++) {
if(array[i] < array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
swap = true;
}
}
}
}