Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering 2D Point Sorting: A Hands-On Guide to Selection, Insertion, Merge, and Quicksort

Learn how to sort 2D integer points using four classic algorithms—selection, insertion, merge, and quicksort—with practical examples, median coordinate calculation, and performance comparison. Perfect for COM S 228 homework help.

sorting 2D points selection sort insertion sort merge sort quicksort median coordinate point COM S 228 Java sorting algorithms computational geometry algorithm comparison homework help sorting Point class Java AbstractSorter PointScanner sorting performance 2D integer points

Introduction: Why Sorting 2D Points Matters

In computer science, sorting is a fundamental operation that underpins many algorithms. When dealing with 2D points, sorting by x- or y-coordinates is crucial for tasks like finding the median coordinate point (MCP), which has applications in computational geometry, data analysis, and even game development. For instance, in a battle royale game like Fortnite, you might sort player positions to find the center of the remaining players. This tutorial walks you through implementing and comparing four sorting algorithms—selection sort, insertion sort, merge sort, and quicksort—on 2D integer points, exactly as required in COM S 228 Homework 2.

We'll cover the Point class, AbstractSorter hierarchy, and PointScanner class, and show you how to compute the median coordinate point. By the end, you'll understand not just the code, but the performance trade-offs between algorithms.

Understanding the Assignment Structure

Point Class and Comparison

The Point class implements Comparable<Point>. Its compareTo() method first compares x-coordinates; if equal, it compares y-coordinates. This ensures a total ordering. For example, point (3, 5) is less than (5, 2) because 3 < 5. This comparator is used when sorting by x. For sorting by y, we use a separate comparator that compares y first, then x.

AbstractSorter and Subclasses

The abstract class AbstractSorter holds the array of points and provides methods sort(), setComparator(), getPoints(), and getMedian(). Four subclasses implement specific sorting algorithms:

  • SelectionSorter
  • InsertionSorter
  • MergeSorter
  • QuickSorter

Each subclass constructor calls super(pts) and sets the algorithm field. The sort() method in each subclass performs the actual sorting using the comparator set by setComparator().

Implementing the Sorting Algorithms

Selection Sort

Selection sort repeatedly finds the minimum element from the unsorted part and swaps it to the front. Its time complexity is O(n²), making it slow for large datasets. However, it's simple and useful for small n.

public class SelectionSorter extends AbstractSorter {
    public SelectionSorter(Point[] pts) throws IllegalArgumentException {
        super(pts);
        algorithm = "Selection Sort";
    }

    @Override
    public void sort() {
        for (int i = 0; i < points.length - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < points.length; j++) {
                if (pointComparator.compare(points[j], points[minIdx]) < 0) {
                    minIdx = j;
                }
            }
            Point temp = points[i];
            points[i] = points[minIdx];
            points[minIdx] = temp;
        }
    }
}

Insertion Sort

Insertion sort builds the final sorted array one element at a time by inserting each element into its correct position. It's also O(n²) but performs well on nearly sorted data. Imagine sorting a hand of playing cards—this is exactly insertion sort.

public class InsertionSorter extends AbstractSorter {
    public InsertionSorter(Point[] pts) throws IllegalArgumentException {
        super(pts);
        algorithm = "Insertion Sort";
    }

    @Override
    public void sort() {
        for (int i = 1; i < points.length; i++) {
            Point key = points[i];
            int j = i - 1;
            while (j >= 0 && pointComparator.compare(points[j], key) > 0) {
                points[j + 1] = points[j];
                j--;
            }
            points[j + 1] = key;
        }
    }
}

Merge Sort

Merge sort is a divide-and-conquer algorithm that splits the array into halves, recursively sorts them, and merges the sorted halves. It runs in O(n log n) time and is stable. It's like organizing a tournament bracket: divide players into groups, determine winners, then combine results.

public class MergeSorter extends AbstractSorter {
    public MergeSorter(Point[] pts) throws IllegalArgumentException {
        super(pts);
        algorithm = "Merge Sort";
    }

    @Override
    public void sort() {
        mergeSort(points, 0, points.length - 1);
    }

    private void mergeSort(Point[] arr, int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    private void merge(Point[] arr, int left, int mid, int right) {
        // create temporary arrays and merge
    }
}

Quicksort

Quicksort also uses divide-and-conquer but selects a pivot and partitions the array around it. Average case O(n log n), but worst-case O(n²) if pivot is poorly chosen. In practice, it's often faster than merge sort due to lower overhead. Think of it like sorting a playlist: pick a favorite song (pivot), put songs before it that you like less, and after it that you like more, then recursively sort each group.

public class QuickSorter extends AbstractSorter {
    public QuickSorter(Point[] pts) throws IllegalArgumentException {
        super(pts);
        algorithm = "Quicksort";
    }

    @Override
    public void sort() {
        quickSort(points, 0, points.length - 1);
    }

    private void quickSort(Point[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }

    private int partition(Point[] arr, int low, int high) {
        Point pivot = arr[high];
        int i = low - 1;
        for (int j = low; j < high; j++) {
            if (pointComparator.compare(arr[j], pivot) < 0) {
                i++;
                Point temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        Point temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }
}

Computing the Median Coordinate Point

After sorting points by x and then by y, the median coordinate point is simply the point at index points.length / 2 (using integer division). This is because the median of an odd-sized array is the middle element; for even, it's the lower middle (Java truncates). In practice, the MCP may not be an actual input point—it's the point whose x is the median x and y is the median y. For example, with 17 points, the median x is at index 8 (0-based) after sorting by x, and median y is at index 8 after sorting by y. The MCP is (median_x, median_y).

In the PointScanner class, the scan() method performs two rounds: first sort by x (using setComparator(0)) and record the median x, then sort by y and record median y. The MCP is then set.

PointScanner and File Input

The PointScanner class has two constructors: one takes a Point[] array, the other takes a filename. The file contains pairs of integers. For example, the input file might contain:

0 0 -3 -9 0 -10 8 4 3 3 -6 3 -2 1 10 5 -7 -10 5 -2 7 3 10 5 -7 -10 0 8 -1 -6 -10 0 5 5

This represents 17 points. The scanner reads them using hasNextInt() and nextInt(). If the number of integers is odd, an InputMismatchException is thrown.

Comparing Sorting Algorithms

The CompareSorters class uses four PointScanner objects, each with a different algorithm, to scan the same set of points. It measures the sorting time (in nanoseconds) using System.nanoTime() and outputs statistics. This allows you to compare performance. For small datasets (like 17 points), differences may be negligible, but for larger random sets (e.g., 10,000 points), merge sort and quicksort will vastly outperform selection and insertion sorts.

Trend Connection: Sorting in AI and Data Science

Sorting algorithms are not just academic—they're used in machine learning preprocessing, database indexing, and even in recommendation systems. For example, when Netflix sorts movies by predicted rating, it uses efficient sorting. Understanding these algorithms helps you optimize performance in real-world applications.

Conclusion

By implementing selection, insertion, merge, and quicksort for 2D points, you gain deep insight into algorithm design and analysis. The median coordinate point computation is a practical application that ties sorting to geometry. Use this guide to ace your COM S 228 homework and build a solid foundation for more advanced topics.