Core Algorithm Exercises in Java: Sorting, Searching, and Array Manipulation

Merging and Sorting Two Arrays

To combine two integer arrays into a single sorted list, one must first determine the total capacity required to hold elements from both sources. A new array is instantiated with this combined length. Elements from the first array are copied sequentially into the new container, followed by elements from the second array. Finally, a bubble sort algorithm is applied to rearrange the merged elements into ascending order.

int[] firstInput = {1, 7, 9, 11, 13, 15, 17, 19};
int[] secondInput = {2, 4, 6, 8, 10};

int totalLength = firstInput.length + secondInput.length;
int[] mergedData = new int[totalLength];

int cursor = 0;
for (int item : firstInput) {
    mergedData[cursor++] = item;
}
for (int item : secondInput) {
    mergedData[cursor++] = item;
}

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

Bubble Sort Implementation

Bubble sort is a comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted. The pass through the list is repeated n-1 times for an array of size n, with each pass placing the next largest element in its correct final position.

int[] sourceArray = {12, 4, 5, 65, 543};

int size = sourceArray.length;
for (int outer = 0; outer < size - 1; outer++) {
    for (int inner = 0; inner < size - 1 - outer; inner++) {
        if (sourceArray[inner] > sourceArray[inner + 1]) {
            int buffer = sourceArray[inner];
            sourceArray[inner] = sourceArray[inner + 1];
            sourceArray[inner + 1] = buffer;
        }
    }
}

Binary Search Algorithm

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one. The search starts by setting the low and high pointers to the start and end of the array, respectively, and then calculating the middle index.

int[] sortedNumbers = {3, 12, 24, 36, 55, 68, 75, 88, 100};
int target = 24;

int low = 0;
int high = sortedNumbers.length - 1;
boolean found = false;

while (low <= high) {
    int mid = (low + high) / 2;
    
    if (sortedNumbers[mid] == target) {
        System.out.println("Target found at index: " + mid);
        found = true;
        break;
    } else if (sortedNumbers[mid] < target) {
        low = mid + 1;
    } else {
        high = mid - 1;
    }
}

if (!found) {
    System.out.println("Target not present in the array.");
}

Day of Year Calculation

Determining the day of the year involves summing the days of the months preceding the current month and adding the day of the month. Leap years must be accounted for, where February has 29 days instead of 28. A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400.

int[] standardDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] leapDays = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Assuming inputYear, inputMonth, and inputDay are provided via Scanner
int dayOfYearCount = 0;

if ((inputYear % 100 != 0 && inputYear % 4 == 0) || (inputYear % 400 == 0)) {
    for (int i = 0; i < inputMonth - 1; i++) {
        dayOfYearCount += leapDays[i];
    }
} else {
    for (int i = 0; i < inputMonth - 1; i++) {
        dayOfYearCount += standardDays[i];
    }
}
dayOfYearCount += inputDay;

System.out.println("Day of the year: " + dayOfYearCount);

Selection Sort Logic

Selection sort divides the input list into two parts: a sorted sublist of items which is built up from left to right, and a sublist of the remaining unsorted items that occupy the rest of the list. The algorithm proceeds by finding the smallest element in the unsorted sublist and swapping it with the leftmost unsorted element.

int[] dataset = {12, 22, 8, 49, 3};

for (int i = 0; i < dataset.length - 1; i++) {
    int minIdx = i;
    for (int j = i + 1; j < dataset.length; j++) {
        if (dataset[j] < dataset[minIdx]) {
            minIdx = j;
        }
    }
    if (minIdx != i) {
        int swapTemp = dataset[i];
        dataset[i] = dataset[minIdx];
        dataset[minIdx] = swapTemp;
    }
}

Two-Dimensional Array Aggregation

Calculating the total sum of elements in a two-dimensional array, such as aggregating sales data across different quarters and months, requires iterating through each row (dimension one) and then through each element within that row (dimension two). A running total is maintained and updated with every element encountered during the traversal.

int[][] quarterlySales = {
    {22, 66, 44},
    {77, 33, 88},
    {25, 45, 65},
    {11, 66, 99}
};

double grandTotal = 0;

for (int i = 0; i < quarterlySales.length; i++) {
    for (int j = 0; j < quarterlySales[i].length; j++) {
        grandTotal += quarterlySales[i][j];
    }
}

Tags: java algorithms Sorting Arrays Data Structures

Posted on Fri, 02 Oct 2026 16:50:12 +0000 by s2day