Implementing Sorting Algorithms in Java: Solutions for Avoiding Duplicate Value Loss

Dec 03, 2025 · Programming · 9 views · 7.8

Keywords: Java Sorting Algorithms | Array Processing | Duplicate Value Issues

Abstract: This article explores the implementation of integer array sorting in Java without using the Arrays.sort() method. By analyzing a common student assignment problem, it reveals the root cause of data loss when handling duplicate values in the original sorting algorithm. The paper explains in detail how to properly handle duplicate values by improving the algorithm logic, while introducing special value initialization strategies to ensure sorting accuracy. Additionally, it briefly compares other sorting algorithms such as bubble sort, providing comprehensive technical reference for readers.

Problem Background and Algorithm Defect Analysis

In Java programming learning, implementing custom sorting algorithms is a common exercise. A typical assignment requires writing a program to input 10 integer values and display them in ascending or descending order without using the Arrays.sort() method. The student's initial code basically implements the sorting function, but has serious flaws when handling duplicate values. For example, when the input contains multiple identical values (such as three 5s), only one 5 is retained in the output, with the remaining positions filled with default value 0, causing data loss.

Working Principle and Root Cause of the Original Algorithm

The core logic of the original sorting algorithm is based on comparative counting: for each element in the array, count the number of elements smaller than it to determine its position in the ordered array. The code snippet is as follows:

for(int indexL=0;indexL<tenNums.length;indexL++)
{
    greater=0;
    for(int indexR=0;indexR<tenNums.length;indexR++)
    {
        if(tenNums[indexL]>tenNums[indexR])
        {
            greater++;
        }
    }
    orderedNums[greater]=tenNums[indexL];
}

The flaw in this approach is that when multiple elements have the same value, they all calculate the same greater value, causing later processed elements to overwrite the position of previous elements in the orderedNums array. Since Java arrays are initialized to 0 by default, unassigned index positions display as 0, resulting in data loss and incorrect output.

Improved Solution: Algorithm Optimization for Handling Duplicate Values

To address the above problem, the optimal solution is to check whether the target position is already occupied by the same value before assignment. By adding a loop to find the next available position, all duplicate values can be correctly stored. The improved code logic is as follows:

while (orderedNums[greater] == tenNums[indexL]) {
    greater++;
}
orderedNums[greater] = tenNums[indexL];

This code increments the greater index until finding a free position when the current position is already occupied by the same value. This method simply and effectively solves the problem of duplicate value overwriting, but attention must be paid to array boundary checks to avoid index out-of-bounds errors.

Special Considerations for Array Initialization

Since the improved algorithm relies on comparison with existing values to detect position occupancy, it must ensure that the initial state of the ordered array does not conflict with input values. If the input may contain 0, the default array initialization (all elements as 0) will cause misjudgment. The solution is to initialize with a special value that cannot appear in the input, such as Integer.MAX_VALUE:

int orderedNums[] = new int[10];
Arrays.fill(orderedNums, Integer.MAX_VALUE);

Alternatively, if the input range is determined, other appropriate values can be chosen. This initialization strategy ensures the reliability of the comparison logic, avoiding sorting errors caused by interference from initial values.

Reference Implementation of Other Sorting Algorithms

In addition to the above improved solution, common sorting algorithms such as bubble sort can also be used for this task. Bubble sort implements sorting through adjacent element comparison and exchange, naturally handling duplicate values without data loss. An example implementation is as follows:

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

Although bubble sort has higher time complexity (O(n²)), it is simple to implement and suitable for small-scale data sorting exercises. Compared with the original algorithm, it does not require additional handling of duplicate value problems, as swap operations do not cause data overwriting loss.

Complete Program Implementation and User Interaction

Combining the above improvements, the complete program should include input processing, sorting algorithm, ascending/descending order selection, and output. The key parts are as follows:

// Initialize ordered array
int orderedNums[] = new int[10];
for (int i = 0; i < orderedNums.length; i++) {
    orderedNums[i] = Integer.MAX_VALUE;
}

// Improved sorting algorithm
for(int indexL = 0; indexL < tenNums.length; indexL++) {
    greater = 0;
    for(int indexR = 0; indexR < tenNums.length; indexR++) {
        if(tenNums[indexL] > tenNums[indexR]) {
            greater++;
        }
    }
    while (orderedNums[greater] == tenNums[indexL]) {
        greater++;
    }
    orderedNums[greater] = tenNums[indexL];
}

The program obtains the user's sorting direction choice through Scanner and outputs ascending or descending results accordingly. This implementation not only solves the duplicate value problem but also maintains code clarity and educational value.

Conclusion and Extended Considerations

This article analyzes in detail the key issue of handling duplicate values in custom sorting algorithms and provides effective solutions. Through algorithm optimization and appropriate initialization strategies, sorting result accuracy can be ensured. For learners, understanding the logic behind algorithms is more important than merely implementing functions. Additionally, exploring implementations of different sorting algorithms (such as selection sort, insertion sort) can deepen understanding of data structures and algorithm efficiency. In actual development, although Arrays.sort() provides efficient sorting, mastering basic principles is crucial for solving complex problems.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.