Logo

dev-resources.site

for different kinds of informations.

Searching vs. Sorting in Java: Key Differences and Applications

Published at
1/16/2025
Categories
java
algorithms
coding
programming
Author
alex_ricciardi
Author
14 person written this
alex_ricciardi
open
Searching vs. Sorting in Java: Key Differences and Applications

This article describes the differences between searching and sorting algorithms in Java, their distinct purposes, methodologies, and time complexities. It includes practical examples and implementations, such as Merge Sort for organizing data and Binary Search for efficient retrieval, demonstrating their roles in solving real-world problems.


In Java, understanding searching and sorting algorithms and how they differ from each other, is crucial for the correct functionality of the application and for effectively managing data. While searching focuses on locating specific data within a collection, sorting rearranges data. This article explores their differences in purpose, methodology, and applications, by providing examples.

The major differences between searching and sorting in Java lie in their purposes and outputs, as well as their efficiencies and time complexities. Please Table 1 for a detailed comparison.

Table 1
Searching vs Sorting in Java
Searching vs Sorting in Java Table

Choosing between different searching or sorting algorithms often depends on the purpose or output wanted and the specific requirements of your application, such as the size of the dataset, and whether the data is already sorted.

The following table, Table 2, gives examples of pseudocode and time complexity for several searches and sort algorithms:

Table 2
Runtime Complexities for Various Pseudocode Examples
Runtime Complexities for Various Pseudocode Examples Table
Note: In Java without using the Comparable Interface the code above would only be viable for primitive types. From Programming in Java with ZyLabs, 18.3 O notation, Figure 18.3.2 by Lysecky, R., & Lizarraga, A. (2022).

An example of a sort algorithm is the merge sort, which has the divide-and-conquer approach, it recursively divides a data array into smaller subarrays and sorts those subarrays, then merges the subarrays together to create a sorted array (GeeksforGeeks, 2020a).An example of a search algorithm is the binary search; which operates on a pre-sorted array by repeatedly dividing the search interval in half until the target element is found or determined to be absent (GeeksforGeeks, 2020b).

The example below sorts using merge sort an ArrayList of book objects by year of publication then searches the sorted list using binary:
Book.java

/**
 * Book object with a title and publication year. This class implements
 * Comparable to allow sorting based on the publication year.
 * 
 * @author Alexander Ricciardi
 * @version 1.0
 * @date 07/14/2024
 */
class Book implements Comparable {
    String title;
    int year;

    /**
     * Constructs a new Book object.
     *
     * @param title The title of the book.
     * @param year  The year the book was published.
     */
    public Book(String title, int year) {
    this.title = title;
    this.year = year;
    }

    /**
     * Compares this book with another book based on the publication year.
     *
     * @param other The book to compare with.
     * @return A negative integer, zero, or a positive integer as this book is less
     *         than, equal to, or greater than the specified book.
     */
    @Override
    public int compareTo(Book other) {
    return Integer.compare(this.year, other.year);
    }

    /**
     * Returns a string representation of the book.
     *
     * @return A string in the format "title (year)".
     */
    @Override
    public String toString() {
    return title + " (" + year + ")";
    }
}
Enter fullscreen mode Exit fullscreen mode

BookSortingSearching.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Sorts and search a list of books. It implements merge sort for sorting and
 * binary search for searching.
 * 
 * @author Alexander Ricciardi
 * @version 1.0
 * @date 07/14/2024
 */
public class BookSortingSearching {

    /**
     * The main method that demonstrates sorting and searching on a list of books.
     *
     * @param args Command line arguments (not used).
     */
    public static void main(String[] args) {
    // Initialize the list of books
    ArrayList books = new ArrayList<>(
        Arrays.asList(
                     new Book("To Kill a Mockingbird", 1960), 
                     new Book("1984", 1949),
                     new Book("The Great Gatsby", 1925),
                     new Book("One Hundred Years of Solitude", 1967),
                     new Book("The Catcher in the Rye", 1951), 
                     new Book("Brave New World", 1932),
                     new Book("The Hobbit", 1937), 
                     new Book("The Lord of the Rings", 1954),
                     new Book("Pride and Prejudice", 1813), 
                     new Book("Animal Farm", 1945)
                 ));

    // Print the original list
    System.out.println("Original list:");
    books.forEach(System.out::println);

    // Sort the books using merge sort
    mergeSort(books, 0, books.size() - 1);

    // Print the sorted list
    System.out.println("\nSorted list by year:");
    books.forEach(System.out::println);

    // Perform binary search based on user input
    Scanner scn = new Scanner(System.in);
    System.out.print("\nEnter a year to search for: ");
    int searchYear = scn.nextInt();

    int result = binarySearch(books, searchYear);
    if (result != -1) {
        System.out.println("Book found: " + books.get(result));
    } else {
        System.out.println("No book found for the year " + searchYear);
    }
    scn.close();
    }

    /**
     * Sorts the given list of books using the merge sort algorithm.
     *
     * @param books The list of books to sort.
     * @param left  The starting index of the subarray to sort.
     * @param right The ending index of the subarray to sort.
     */
    private static void mergeSort(ArrayList books, int left, int right) {
    if (left < right) {
        int mid = (left + right) / 2;
        mergeSort(books, left, mid); // Sort left half
        mergeSort(books, mid + 1, right); // Sort right half
        merge(books, left, mid, right); // Merge the sorted halves
    }
    }

    /**
     * Merges two sorted subarrays of the books list.
     *
     * @param books The list of books containing the subarrays to merge.
     * @param left  The starting index of the left subarray.
     * @param mid   The ending index of the left subarray.
     * @param right The ending index of the right subarray.
     */
    private static void merge(ArrayList books, int left, int mid, int right) {
    // Create temporary arrays
    ArrayList leftList = new ArrayList<>(books.subList(left, mid + 1));
    ArrayList rightList = new ArrayList<>(books.subList(mid + 1, right + 1));

    int i = 0, j = 0, k = left;

    // Merge the two lists
    while (i < leftList.size() && j < rightList.size()) {
        if (leftList.get(i).compareTo(rightList.get(j)) <= 0) {
        books.set(k++, leftList.get(i++));
        } else {
        books.set(k++, rightList.get(j++));
        }
    }

    // Copy remaining elements of leftList, if any
    while (i < leftList.size()) {
        books.set(k++, leftList.get(i++));
    }

    // Copy remaining elements of rightList, if any
    while (j < rightList.size()) {
        books.set(k++, rightList.get(j++));
    }
    }

    /**
     * Performs a binary search on the sorted list of books to find a book by its
     * publication year.
     *
     * @param books The sorted list of books to search.
     * @param year  The publication year to search for.
     * @return The index of the book if found, -1 otherwise.
     */
    private static int binarySearch(ArrayList books, int year) {
    int left = 0, right = books.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (books.get(mid).year == year) {
        return mid; // Book found
        }
        if (books.get(mid).year < year) {
        left = mid + 1; // Search in the right half
        } else {
        right = mid - 1; // Search in the left half
        }
    }
    return -1; // Book not found
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

To Kill a Mockingbird (1960)
1984 (1949)
The Great Gatsby (1925)
One Hundred Years of Solitude (1967)
The Catcher in the Rye (1951)
Brave New World (1932)
The Hobbit (1937)
The Lord of the Rings (1954)
Pride and Prejudice (1813)
Animal Farm (1945)

Sorted list by year:
Pride and Prejudice (1813)
The Great Gatsby (1925)
Brave New World (1932)
The Hobbit (1937)
Animal Farm (1945)
1984 (1949)
The Catcher in the Rye (1951)
The Lord of the Rings (1954)
To Kill a Mockingbird (1960)
One Hundred Years of Solitude (1967)

Enter a year to search for: 1951
Book found: The Catcher in the Rye (1951)
Enter fullscreen mode Exit fullscreen mode

In other words, merge sort is efficient for sorting large sets of data due to its complexity of O(n log(n)), while binary search with its targeted approach to search is better suited for machine learning applications, such as those for training neural networks or finding the optimal hyperparameters for a model.

In summary, searching and sorting algorithms have interconnected roles in programming but serve different purposes. Sorting algorithms like Merge Sort organize the data, allowing searching methods such as Binary Search to be more efficient. Together, these algorithms are indispensable for solving real-world problems, from data analysis to application development.


References:

GeeksforGeeks. (2020a, November 18). Merge sort. GeeksforGeeks https://www.geeksforgeeks.org/merge-sort/

GeeksforGeeks. (2020b, February 3). Binary search. GeeksforGeeks. https://www.geeksforgeeks.org/binary-search/

Lysecky, R., & Lizarraga, A. (2022)._ Programming in Java with ZyLabs_[ Table]. Zyante, Inc.


Originally published at Alex.omegapy on Medium by Level UP Coding on November 22, 2024.

programming Article's
30 articles in total
Programming is the process of writing, testing, and maintaining code to create software applications for various purposes and platforms.
Favicon
What ((programming) language) should I learn this year, 2025 ?
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
Designing for developers means designing for LLMs too
Favicon
Introduction to TypeScript for JavaScript Developers
Favicon
Filling a 10 Million Image Grid with PHP for Internet History
Favicon
When AI Fails, Good Documentation Saves the Day 🤖📚
Favicon
Is JavaScript Still Relevant?
Favicon
Daily JavaScript Challenge #JS-74: Convert Hexadecimal to Binary
Favicon
Code Smell 286 - Overlapping Methods
Favicon
Searching vs. Sorting in Java: Key Differences and Applications
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
Securing Sensitive Data in Java: Best Practices and Coding Guidelines
Favicon
Golang - How a Chef and Waiter Teach the Single Responsibility Principle
Favicon
[Boost]
Favicon
How to Resolve the 'Permission Denied' Error in PHP File Handling
Favicon
7 Mistakes Developers Make When Learning a New Framework (and How to Avoid Them)
Favicon
Python в 2025: стоит ли начинать с нуля? Личный опыт и рекомендации
Favicon
Cómo gestionar tus proyectos de software con Github
Favicon
2429. Minimize XOR
Favicon
Decreasing server load by using debouncing/throttle technique in reactjs
Favicon
➡️💡Guide, Innovate, Succeed: Becoming a Software Development Leader 🚀
Favicon
Debugging Adventure Day 1: What to Do When Your Code Doesn’t Work
Favicon
🚀 New Book Release: "Navigate the Automation Seas" – A Practical Guide to Building Automation Frameworks
Favicon
Build a Secure Password Generator with Javascript
Favicon
join my project semester simulator
Favicon
Как создать свой VPN и получить доступ ко всему?
Favicon
Основы изучения Python: Руководство для начинающих
Favicon
Revolutionary AI Model Self-Adapts Like Human Brain: Transformer Shows 15% Better Performance in Complex Tasks
Favicon
Breakthrough: Privacy-First AI Splits Tasks Across Devices to Match Central Model Performance
Favicon
Flow Networks Breakthrough: New Theory Shows Promise for Machine Learning Structure Discovery

Featured ones: