This code-along guides you through implementing and analyzing various sorting algorithms including Bubble Sort, Selection Sort, Insertion Sort, and Quick Sort. You'll learn about their runtime complexity and practical applications while working through Java implementations.
// Example of Bubble Sort implementation public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
This code-along demonstrates how to compare and sort different types of objects in Java. You'll implement both the Comparable interface for natural ordering and Comparator classes for custom comparison logic. The code-along uses fruit classes (like Apple and Orange) to illustrate how to meaningfully compare dissimilar objects.
// Implementing Comparable in a custom class public class Apple implements Comparable<Apple> { private String variety; private double weight; private double price; // Constructor and getters/setters... @Override public int compareTo(Apple other) { // Compare apples based on price return Double.compare(this.price, other.price); } } // Creating a custom Comparator public class FruitWeightComparator implements Comparator<Fruit> { @Override public int compare(Fruit f1, Fruit f2) { return Double.compare(f1.getWeight(), f2.getWeight()); } }