Popular Searches
Popular Course Categories
Popular Courses

Performing Array Searching, Sorting, and Copying Operations

Performing Array Searching, Sorting, and Copying Operations

Arrays and Multidimensional Arrays

Performing Array Searching, Sorting, and Copying Operations in Java

Course: Core Java Training

Topic: Performing Array Searching, Sorting, and Copying Operations

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction

Arrays are fundamental data structures in Java that store multiple values of the same declared component type. After creating an array, programs often need to locate particular values, arrange elements in a specific order, or create copies for further processing.

Searching identifies whether an element exists and, when appropriate, determines its index. Sorting arranges elements in ascending or descending order. Copying creates another array containing elements from the original array.

These operations are useful in student record systems, employee management applications, inventory programs, financial calculations, and many other software applications.

2. Learning Objectives

  • Understand the purpose of array searching, sorting, and copying.
  • Perform linear search on an array.
  • Understand binary search and its sorted-array requirement.
  • Sort arrays using Java's built-in Arrays.sort() method.
  • Understand ascending and descending order.
  • Copy arrays using assignment, loops, clone(), and Arrays.copyOf().
  • Understand shallow copying and reference sharing.
  • Compare the time complexity of common operations.
  • Handle empty arrays, duplicate elements, and invalid inputs safely.
  • Apply these techniques in practical Java programs.

3. Understanding Array Searching

Array searching is the process of locating a specific element in an array. The value being searched for is called the target or search key.

A search operation may return the index of the target, a boolean result indicating whether it exists, or another suitable result depending on the application's requirements.

Example

int[] numbers = {10, 20, 30, 40, 50};
int target = 30;

The target value is 30, which is located at index 2.

4. Linear Search

Linear search checks each array element sequentially, starting from the first element. It stops when the target is found or when all elements have been checked.

Linear search works with both sorted and unsorted arrays, making it a simple and flexible searching technique.

Algorithm

  1. Start at index zero.
  2. Compare the current element with the target.
  3. If they match, return the current index.
  4. If they do not match, move to the next element.
  5. If the end of the array is reached without a match, report that the target was not found.

Java Program: Linear Search

public class LinearSearchExample {
    public static void main(String[] args) {
        int[] numbers = {15, 25, 35, 45, 55};
        int target = 35;
        int foundIndex = -1;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                foundIndex = i;
                break;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Element found at index: " + foundIndex);
        } else {
            System.out.println("Element not found");
        }
    }
}

Output:

Element found at index: 2

Explanation

  • The array contains five integer values.
  • The target is 35.
  • The loop compares each element with the target.
  • When the value is found at index two, the program stores the index and exits the loop using break.
  • The value -1 is used as a marker meaning that no match was found.

5. Linear Search with a Reusable Method

Creating a method makes the search operation reusable across different arrays and target values.

public class LinearSearchMethod {
    static int search(int[] values, int target) {
        if (values == null) {
            return -1;
        }

        for (int i = 0; i < values.length; i++) {
            if (values[i] == target) {
                return i;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] values = {5, 12, 18, 24, 30};

        int result = search(values, 24);

        if (result == -1) {
            System.out.println("Value not found");
        } else {
            System.out.println("Value found at index: " + result);
        }
    }
}

Output:

Value found at index: 3

This method returns the index of the first matching element. It returns -1 if the target is not found or the array reference is null.

6. Searching for Duplicate Values

An array can contain the same value more than once. A linear search that returns immediately after a match finds only the first occurrence.

public class DuplicateSearchExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 20, 40};
        int target = 20;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                System.out.println("Found at index: " + i);
            }
        }
    }
}

Output:

Found at index: 1
Found at index: 3

To find every occurrence, do not use break after the first match. Continue checking the remaining elements.

7. Binary Search

Binary search is an efficient searching algorithm that repeatedly divides the search range into two halves. It compares the target with the middle element and eliminates the half that cannot contain the target.

Important requirement: Binary search requires the array to be sorted according to the ordering used by the search. Applying it to an unsorted array may produce an incorrect result.

Algorithm

  1. Set the lower boundary to the first index and the upper boundary to the last index.
  2. Calculate the middle index.
  3. If the middle element equals the target, return its index.
  4. If the target is smaller, continue searching the left half.
  5. If the target is larger, continue searching the right half.
  6. Repeat until the target is found or the search range becomes empty.

Java Program: Binary Search

public class BinarySearchExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60, 70};
        int target = 50;

        int left = 0;
        int right = numbers.length - 1;
        int foundIndex = -1;

        while (left <= right) {
            int middle = left + (right - left) / 2;

            if (numbers[middle] == target) {
                foundIndex = middle;
                break;
            } else if (numbers[middle] < target) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Element found at index: " + foundIndex);
        } else {
            System.out.println("Element not found");
        }
    }
}

Output:

Element found at index: 4

8. Binary Search Using Java's Arrays Class

Java provides the Arrays.binarySearch() method for searching sorted arrays. For primitive arrays such as int[], it returns an index when the target is found.

import java.util.Arrays;

public class BuiltInBinarySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60};

        int index = Arrays.binarySearch(numbers, 40);

        if (index >= 0) {
            System.out.println("Found at index: " + index);
        } else {
            System.out.println("Element not found");
        }
    }
}

Output:

Found at index: 3

If the target is not found, Arrays.binarySearch() returns a negative value that encodes an insertion point. When duplicates exist, it does not guarantee which matching index will be returned.

9. Linear Search Versus Binary Search

Feature Linear Search Binary Search
Approach Checks elements one by one Repeatedly halves the search range
Sorted array required No Yes
Worst-case time complexity O(n) O(log n)
Best-case time complexity O(1) O(1)
Ease of implementation Simple Requires careful boundary handling
Suitable use Small or unsorted arrays Sorted arrays with repeated searches

10. Introduction to Array Sorting

Sorting is the process of arranging array elements in a defined order. The most common orders are ascending and descending.

  • Ascending order: Values are arranged from smallest to largest.
  • Descending order: Values are arranged from largest to smallest.

For example, the array {40, 10, 30, 20} becomes {10, 20, 30, 40} when sorted in ascending order.

Sorting makes it easier to analyze data, display records in a consistent order, and use algorithms such as binary search.

11. Sorting with Arrays.sort()

The java.util.Arrays class provides the sort() method for sorting supported array types. For primitive numeric arrays, the method sorts elements in ascending order.

Java Program

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        int[] numbers = {50, 20, 40, 10, 30};

        Arrays.sort(numbers);

        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }
}

Output:

Sorted array: [10, 20, 30, 40, 50]

The Arrays.sort() method modifies the original array. If the original order must be preserved, make a copy before sorting.

12. Sorting a String Array

String arrays can also be sorted using Arrays.sort(). By default, strings are arranged according to their natural ordering, which is lexicographic and case-sensitive.

import java.util.Arrays;

public class StringSortExample {
    public static void main(String[] args) {
        String[] names = {"Ravi", "Amit", "Neha", "Kiran"};

        Arrays.sort(names);

        System.out.println(Arrays.toString(names));
    }
}

Output:

[Amit, Kiran, Neha, Ravi]

For case-insensitive ordering or other custom rules, use an appropriate comparator with a supported object-array sorting overload.

13. Sorting in Descending Order

For an array of primitive integers, one straightforward way to obtain descending order is to sort it in ascending order and then reverse the elements.

import java.util.Arrays;

public class DescendingSortExample {
    public static void main(String[] args) {
        int[] numbers = {15, 5, 35, 25, 10};

        Arrays.sort(numbers);

        int left = 0;
        int right = numbers.length - 1;

        while (left < right) {
            int temp = numbers[left];
            numbers[left] = numbers[right];
            numbers[right] = temp;

            left++;
            right--;
        }

        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[35, 25, 15, 10, 5]

This approach sorts the original array and then reverses it. For object arrays, descending order can also be implemented using a comparator.

14. Bubble Sort

Bubble sort is a simple comparison-based sorting algorithm. It repeatedly compares adjacent elements and swaps them when they are in the wrong order.

Algorithm

  1. Start from the first element.
  2. Compare each pair of adjacent elements.
  3. Swap them if the left element is greater than the right element.
  4. Continue through the array; the largest unsorted value moves toward the end.
  5. Repeat until the array is sorted or a complete pass makes no swaps.

Java Program

import java.util.Arrays;

public class BubbleSortExample {
    public static void main(String[] args) {
        int[] numbers = {5, 1, 4, 2, 8};

        for (int i = 0; i < numbers.length - 1; i++) {
            boolean swapped = false;

            for (int j = 0; j < numbers.length - 1 - i; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                    swapped = true;
                }
            }

            if (!swapped) {
                break;
            }
        }

        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[1, 2, 4, 5, 8]

Bubble sort is useful for learning sorting logic, but it is inefficient for large arrays. Its average and worst-case time complexity is O(n²).

15. Selection Sort

Selection sort repeatedly finds the smallest element in the unsorted portion and swaps it with the first element of that portion.

import java.util.Arrays;

public class SelectionSortExample {
    public static void main(String[] args) {
        int[] numbers = {64, 25, 12, 22, 11};

        for (int i = 0; i < numbers.length - 1; i++) {
            int minIndex = i;

            for (int j = i + 1; j < numbers.length; j++) {
                if (numbers[j] < numbers[minIndex]) {
                    minIndex = j;
                }
            }

            int temp = numbers[i];
            numbers[i] = numbers[minIndex];
            numbers[minIndex] = temp;
        }

        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[11, 12, 22, 25, 64]

Selection sort has O(n²) time complexity in the best, average, and worst cases. It is useful for understanding selection-based sorting but is generally not the preferred choice for large data sets.

16. Comparing Sorting Algorithms

Algorithm Best Case Average Case Worst Case Notes
Bubble sort with early exit O(n) O(n²) O(n²) Easy to understand; many comparisons and swaps
Selection sort O(n²) O(n²) O(n²) Performs relatively few swaps
Insertion sort O(n) O(n²) O(n²) Effective for small or nearly sorted arrays
Java's Arrays.sort() Depends on type and implementation Generally efficient Depends on type and implementation Prefer the standard library for normal application code

Exact performance characteristics of Java's built-in sorting methods depend on the array type and Java implementation. Use the standard library unless a custom algorithm is required for learning or a specific application need.

17. Understanding Array Copying

Array copying means creating a new array and copying element values or references from an existing array. Copying is useful when the original data must remain unchanged while another version is sorted or modified.

There are several ways to copy arrays in Java, and each method has different implications.

18. Copying an Array Using Assignment

Assigning one array variable to another does not create a new array. Both variables refer to the same array object.

import java.util.Arrays;

public class ArrayAssignmentExample {
    public static void main(String[] args) {
        int[] original = {10, 20, 30};
        int[] reference = original;

        reference[0] = 100;

        System.out.println(Arrays.toString(original));
        System.out.println(Arrays.toString(reference));
    }
}

Output:

[100, 20, 30]
[100, 20, 30]

Explanation: The assignment copies the reference, not the array. Changing an element through either variable changes the same underlying array.

19. Copying an Array Using a for Loop

A manual loop can copy each element into a newly created array. This method is helpful for learning how copying works and for applying custom rules while copying.

import java.util.Arrays;

public class ManualArrayCopy {
    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40};
        int[] copied = new int[original.length];

        for (int i = 0; i < original.length; i++) {
            copied[i] = original[i];
        }

        copied[0] = 100;

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Copied: " + Arrays.toString(copied));
    }
}

Output:

Original: [10, 20, 30, 40]
Copied: [100, 20, 30, 40]

The program creates a separate integer array and copies each value into it. Changes to the copied primitive array do not affect the original array.

20. Copying an Array Using Arrays.copyOf()

The Arrays.copyOf() method creates a new array of the requested length and copies elements from the original array.

Syntax

Arrays.copyOf(originalArray, newLength)

Example

import java.util.Arrays;

public class CopyOfExample {
    public static void main(String[] args) {
        int[] original = {10, 20, 30};

        int[] copied = Arrays.copyOf(original, original.length);

        System.out.println(Arrays.toString(copied));
    }
}

Output:

[10, 20, 30]

If the requested length is larger than the original array, extra positions receive the default values for the component type. If the requested length is smaller, only the first requested number of elements is copied.

Example: Increasing the Array Length

import java.util.Arrays;

public class ExpandArrayExample {
    public static void main(String[] args) {
        int[] original = {10, 20, 30};

        int[] expanded = Arrays.copyOf(original, 5);

        System.out.println(Arrays.toString(expanded));
    }
}

Output:

[10, 20, 30, 0, 0]

21. Copying an Array Using clone()

Arrays inherit the clone() method, which creates a new array with the same length and copies the element values or references into it.

import java.util.Arrays;

public class CloneArrayExample {
    public static void main(String[] args) {
        int[] original = {5, 10, 15};
        int[] copied = original.clone();

        copied[1] = 100;

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Copied: " + Arrays.toString(copied));
    }
}

Output:

Original: [5, 10, 15]
Copied: [5, 100, 15]

For a primitive array, cloning creates an independent array of primitive values. For an object array, the array is new, but its elements still refer to the same objects as the original array.

22. Copying an Array Using System.arraycopy()

The System.arraycopy() method copies a specified range of elements from one array into another array. It is useful when only part of an array needs to be copied or when copying into an existing destination array.

Syntax

System.arraycopy(source, sourcePosition, destination,
                 destinationPosition, length);

Example

import java.util.Arrays;

public class SystemArrayCopyExample {
    public static void main(String[] args) {
        int[] source = {10, 20, 30, 40, 50};
        int[] destination = new int[3];

        System.arraycopy(source, 1, destination, 0, 3);

        System.out.println(Arrays.toString(destination));
    }
}

Output:

[20, 30, 40]

Explanation: Copying starts at source index one and copies three elements into destination index zero. The destination array must have sufficient capacity for the requested range.

23. Shallow Copying and Deep Copying

Understanding the difference between shallow and deep copying is important when arrays store object references.

  • Shallow copy: Creates a new array but copies references to the same objects.
  • Deep copy: Creates a new array and separately copies or recreates the referenced objects, according to the application's requirements.

Example: Shallow Copy of an Object Array

import java.util.Arrays;

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}

public class ShallowCopyExample {
    public static void main(String[] args) {
        Student[] original = {
            new Student("Amit")
        };

        Student[] copied = original.clone();

        copied[0].name = "Riya";

        System.out.println(original[0].name);
        System.out.println(Arrays.toString(
            new String[]{copied[0].name}
        ));
    }
}

Output:

Riya
[Riya]

Explanation: The two arrays are different array objects, but both elements refer to the same Student object. Updating that student's name through the copied array is therefore visible through the original array too.

Deep copying requires an explicit strategy for the object type. It may involve copy constructors, mapping each element to a new object, or another suitable approach. A simple array clone does not perform a deep copy.

24. Copying and Sorting Without Changing the Original

A common practical requirement is to sort a copy while preserving the original order. First create a copy, then sort the copied array.

import java.util.Arrays;

public class CopyAndSortExample {
    public static void main(String[] args) {
        int[] original = {40, 10, 30, 20};
        int[] sorted = Arrays.copyOf(original, original.length);

        Arrays.sort(sorted);

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Sorted copy: " + Arrays.toString(sorted));
    }
}

Output:

Original: [40, 10, 30, 20]
Sorted copy: [10, 20, 30, 40]

This technique is useful when the original sequence must be retained for display, comparison, auditing, or further processing.

25. Copying a Specific Range of an Array

Sometimes an application needs only a portion of an array rather than the complete array. The Arrays.copyOfRange() method creates a new array containing elements from a specified range.

Syntax

Arrays.copyOfRange(original, from, to)

The starting index is inclusive, while the ending index is exclusive.

Java Program

import java.util.Arrays;

public class CopyArrayRangeExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60};

        int[] portion = Arrays.copyOfRange(numbers, 1, 4);

        System.out.println(Arrays.toString(portion));
    }
}

Output:

[20, 30, 40]

Explanation: The method copies elements at indexes one, two, and three. Index four is excluded from the range.

26. Comparing Array Copying Methods

Method Creates a New Array? Copies Part of an Array? Important Detail
Assignment (b = a) No No Both variables refer to the same array.
Manual loop When destination is separately created Yes, with custom logic Provides complete control over the copying process.
Arrays.copyOf() Yes Copies from the beginning Can create a shorter or longer array.
clone() Yes No, copies the entire array Creates a shallow copy.
System.arraycopy() No, destination must exist Yes Copies a specified number of elements into an existing array.
Arrays.copyOfRange() Yes Yes Copies a selected range into a new array.

27. Searching, Sorting, and Copying Together

These operations are often combined in real applications. For example, a program can preserve an original list of prices, sort a separate copy, and search the sorted copy for a particular price.

Complete Java Program

import java.util.Arrays;

public class ArrayOperationsExample {
    public static void main(String[] args) {
        int[] prices = {450, 200, 350, 100, 500};

        // Create an independent copy.
        int[] sortedPrices = Arrays.copyOf(
            prices, prices.length
        );

        // Sort the copied array.
        Arrays.sort(sortedPrices);

        // Search for a price in the sorted array.
        int target = 350;
        int index = Arrays.binarySearch(sortedPrices, target);

        System.out.println(
            "Original prices: " + Arrays.toString(prices)
        );
        System.out.println(
            "Sorted prices: " + Arrays.toString(sortedPrices)
        );

        if (index >= 0) {
            System.out.println(
                "Price found at sorted index: " + index
            );
        } else {
            System.out.println("Price not found");
        }
    }
}

Output:

Original prices: [450, 200, 350, 100, 500]
Sorted prices: [100, 200, 350, 450, 500]
Price found at sorted index: 2

Program Explanation

  1. The prices array stores the original price values.
  2. Arrays.copyOf() creates an independent copy.
  3. Arrays.sort() arranges the copied values in ascending order.
  4. Arrays.binarySearch() searches for the target in the sorted copy.
  5. The original array remains unchanged.

Important: The index returned by binary search refers to the sorted array, not the corresponding position in the original array.

28. Time Complexity of Array Operations

Time complexity describes how an algorithm's work grows as the number of elements increases. The following table summarizes common operations.

Operation Typical Time Complexity Explanation
Access by index O(1) Directly accesses a specific element.
Linear search O(n) worst case May inspect every element.
Binary search O(log n) worst case Repeatedly halves a sorted search range.
Bubble sort O(n²) average and worst case Repeatedly compares adjacent elements.
Selection sort O(n²) Repeatedly scans the unsorted portion.
Copying all elements O(n) Copies each element once.
Reversing in place O(n) Swaps elements from opposite ends.
Java built-in sorting Depends on array type and implementation Usually preferred over handwritten sorting for application code.

Here, n represents the number of elements. Binary search is particularly useful when the array is already sorted and multiple searches must be performed.

29. Common Errors and Troubleshooting

Problem Cause Solution
ArrayIndexOutOfBoundsException Using an invalid index while searching or copying. Check array length and index boundaries.
Binary search returns an unexpected result The array is not sorted according to the expected ordering. Sort the array first or use linear search.
Original array changes unexpectedly Two variables reference the same array. Create a separate copy using an appropriate copying method.
Search does not find an existing value The target comparison or search range is incorrect. Check the target, loop condition, and boundaries.
Copy contains unexpected zeros or nulls The requested destination length exceeds the number of copied elements. Understand the default initialization of additional positions.
NullPointerException The array reference is null. Initialize the array or check for null before using it.
Sorting changes the original sequence Arrays.sort() sorts the array passed to it. Copy the array before sorting if the original order must be preserved.
Object changes appear in both arrays A shallow copy retains references to the same objects. Perform an appropriate deep copy if independent objects are required.

30. Best Practices

  • Use linear search when the array is small or unsorted.
  • Use binary search only when the array is sorted according to the search ordering.
  • Use Arrays.sort() for ordinary array sorting unless a custom algorithm is needed.
  • Use Arrays.toString() to inspect one-dimensional arrays during debugging.
  • Use Arrays.copyOf() or clone() when a separate array is required.
  • Remember that assignment copies a reference, not an array.
  • Understand the difference between shallow copying and deep copying.
  • Validate array references and indexes before accessing elements when inputs may be invalid.
  • Handle empty arrays explicitly before accessing index zero.
  • Use descriptive method names such as search(), sortPrices(), and copyArray().
  • Test arrays containing duplicate values, negative values, a single element, and no elements.
  • Consider memory usage when creating multiple copies of large arrays.

31. Practical Project: Product Price Manager

Create a Java program that stores product prices, displays the original list, sorts a copy of the prices, searches for a selected price, and prints the results without modifying the original list.

Java Program

import java.util.Arrays;

public class ProductPriceManager {
    public static void main(String[] args) {
        int[] prices = {799, 299, 999, 499, 599};

        System.out.println(
            "Original prices: " + Arrays.toString(prices)
        );

        int[] sortedPrices = Arrays.copyOf(
            prices, prices.length
        );

        Arrays.sort(sortedPrices);

        System.out.println(
            "Sorted prices: " + Arrays.toString(sortedPrices)
        );

        int targetPrice = 599;
        int index = Arrays.binarySearch(
            sortedPrices, targetPrice
        );

        if (index >= 0) {
            System.out.println(
                "Price " + targetPrice +
                " found at sorted index " + index
            );
        } else {
            System.out.println(
                "Price " + targetPrice + " was not found"
            );
        }

        System.out.println(
            "Original prices after processing: " +
            Arrays.toString(prices)
        );
    }
}

Output:

Original prices: [799, 299, 999, 499, 599]
Sorted prices: [299, 499, 599, 799, 999]
Price 599 found at sorted index 2
Original prices after processing: [799, 299, 999, 499, 599]

Project Requirements

  • Store at least five product prices in an integer array.
  • Display the original prices.
  • Create a separate copy of the array.
  • Sort the copy in ascending order.
  • Search for a selected price using binary search.
  • Display whether the target was found.
  • Verify that the original array remains unchanged.

32. Practice Exercises

Beginner-Level Exercises

  1. Write a program that searches for a number using linear search.
  2. Modify the search program to print all indexes where the target occurs.
  3. Sort five integers in ascending order using Arrays.sort().
  4. Copy an integer array using a for loop.
  5. Demonstrate the difference between array assignment and creating a copy.

Intermediate-Level Exercises

  1. Implement binary search for a sorted integer array.
  2. Sort an array in descending order.
  3. Implement bubble sort and display the sorted values.
  4. Copy only a selected range of an array.
  5. Create a sorted copy while preserving the original array.
  6. Compare two arrays using Arrays.equals().
  7. Search an array containing duplicate values and display every matching index.

Advanced-Level Exercises

  1. Implement insertion sort and compare it with bubble sort.
  2. Merge two sorted arrays into a new sorted array.
  3. Write a method that returns the first occurrence of a target value.
  4. Write a method that finds the insertion position for a target in a sorted array.
  5. Create an object array, make a shallow copy, and demonstrate shared object references.
  6. Build a product inventory program that sorts product prices and searches for selected values.

33. Interview Questions and Answers

Q1. What is linear search?

Answer: Linear search checks elements sequentially until the target is found or all elements have been examined. It works with sorted and unsorted arrays.

Q2. What is binary search?

Answer: Binary search repeatedly halves a search range. It requires the array to be sorted according to the ordering used by the search.

Q3. What is the time complexity of linear search?

Answer: Its worst-case time complexity is O(n), because it may need to inspect every element.

Q4. What is the time complexity of binary search?

Answer: Its worst-case time complexity is O(log n) on a sorted array.

Q5. How do you sort an integer array in Java?

Answer: Import java.util.Arrays and call Arrays.sort(array). For primitive integer arrays, this sorts the values in ascending order.

Q6. Does Arrays.sort() modify the original array?

Answer: Yes. It sorts the array passed to the method. Create a copy first if the original order must be preserved.

Q7. How do you sort an integer array in descending order?

Answer: One approach is to sort the primitive array in ascending order and reverse its elements. Object arrays can also be sorted with a suitable comparator.

Q8. Does assigning one array variable to another create a copy?

Answer: No. Assignment copies the reference, so both variables point to the same array object.

Q9. What is the difference between clone() and Arrays.copyOf()?

Answer: Both create a new array with copied element values or references. clone() copies the complete array, while Arrays.copyOf() allows the new length to be specified.

Q10. What is System.arraycopy() used for?

Answer: It copies a specified number of elements from a source array into an existing destination array.

Q11. What is a shallow copy?

Answer: A shallow copy creates a new array but copies object references, so the original and copied arrays may refer to the same objects.

Q12. What is a deep copy?

Answer: A deep copy creates independent copies of the relevant referenced objects as well as the array structure, according to the application's copying requirements.

Q13. What does Arrays.binarySearch() return when a value is not found?

Answer: It returns a negative value encoding the insertion point. A non-negative result indicates that a matching value was found.

Q14. Does binary search return the first occurrence of a duplicate value?

Answer: Not necessarily. When duplicates exist, Java's Arrays.binarySearch() does not guarantee which matching index it returns.

Q15. How can you preserve an array while sorting it?

Answer: Create a separate copy using Arrays.copyOf() or clone(), then sort the copied array.

34. Quick Revision Checklist

  • Linear search: Checks each element sequentially.
  • Binary search: Efficiently searches a sorted array.
  • Sorting: Arranges values in ascending or descending order.
  • Arrays.sort(): Sorts supported arrays in place.
  • Bubble sort: Compares and swaps adjacent elements.
  • Selection sort: Repeatedly selects the smallest remaining element.
  • Arrays.copyOf(): Creates a copy with a specified length.
  • clone(): Creates a shallow copy of the array.
  • System.arraycopy(): Copies a selected range into an existing destination.
  • Arrays.copyOfRange(): Creates a copy of a specified range.
  • Assignment: Copies an array reference rather than the array.
  • Shallow copy: Copies references to the same objects.
  • Deep copy: Requires separately copying referenced objects when independence is needed.
  • Binary search requirement: The array must be sorted according to the expected ordering.
  • Safe indexing: Valid indexes range from zero to array.length - 1.

35. Conclusion

Searching, sorting, and copying are essential operations when working with one-dimensional arrays in Java. Linear search provides a simple way to find values in any array, while binary search can improve search efficiency when the array is properly sorted. Sorting organizes data for easier analysis and can prepare an array for efficient searching.

Array copying is equally important because it allows a program to preserve original data while processing another version. Understanding the differences between assignment, shallow copying, and deep copying helps prevent unexpected changes to shared data.

Practise the included programs and exercises to strengthen your Core Java skills. Once these techniques become familiar, you can apply them to more advanced problems involving collections, object arrays, data processing, and algorithm design.

Continue learning: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy website.

whatsapp