Algorithms: Bubble Sort

Algorithms: Bubble Sort

Business Problem: Student Performance Ranking

Imagine you are a principal of a small private school and want to rank your students based on their GPA. You have a list of students with their performance scores in an unsorted array. You need to sort this list in descending order so that you can identify the top-performing students easily. Here is an example dataset:

This is how you could use Bubble Sort to solve this problem in JavaScript:

Explanation of the Algorithm

  1. function bubbleSort(arr, comparator): This function takes an array arr to be sorted and a comparator function to determine the order of elements.

  2. let n = arr.length;: We calculate the length of the array arr to determine the number of elements to sort.

  3. let swapped;: This variable will be used to track whether any swaps were made in the current pass.

  4. do { ... } while (swapped);: We use a do...while loop to continue sorting until no more swaps are needed. The loop runs at least once and repeats as long as swapped is true.

  5. swapped = false;: At the start of each pass, we initialize swapped as false.

  6. for (let i = 0; i < n - 1; i++) { ... }: This loop iterates through the array, comparing adjacent elements.

  7. if (comparator(arr[i], arr[i + 1]) > 0) { ... }: We use the comparator function to compare two adjacent elements. If they are in the wrong order (according to the comparator), we swap them.

  8. let temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp;: This is the swapping step. We use a temporary variable temp to swap the elements.

  9. swapped = true;: If a swap occurs, we set swapped to true to indicate that the array is not yet fully sorted.

  10. return arr;: Finally, we return the sorted array once no more swaps are needed.

This Bubble Sort algorithm repeatedly compares and swaps adjacent elements until the entire array is sorted. All that is needed is to call the algorithm with the proper arguments passed to it so that the sort can take place.

The printed results should be as follows:

Conclusion

In this example, the bubbleSort function is used to sort the array of students based on their performance scores in descending order. After sorting, the students array will be reordered, with the highest-performing students appearing first.

Bubble Sort, although not the most efficient sorting algorithm for large datasets, can be suitable for small-scale tasks like this one where simplicity and readability are more important than performance optimization.