You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java选择排序中嵌套实现Dog对象的多级排序?

Combining Selection Sort for Multi-Criteria Dog Sorting

Absolutely you can merge these two selection sort routines into a single block of code to handle your multi-criteria sorting requirement—first by tail length, then by name when tail lengths are identical. The trick is to adjust the comparison logic in the inner loop to check the primary criterion first, and only use the secondary criterion when the primary values are equal.

Modified Single Selection Sort Method

public List<Dog> sortDogsByTailThenName() {
    for (int a = 0; a < listOfDogs.size() - 1; a++) {
        // Track the entire minimum Dog object instead of just a single field
        Dog minDog = listOfDogs.get(a);
        int minIndex = a;
        
        for (int b = a + 1; b < listOfDogs.size(); b++) {
            Dog currentDog = listOfDogs.get(b);
            // First compare tail lengths (primary sorting criterion)
            if (currentDog.getTailLength() < minDog.getTailLength()) {
                minDog = currentDog;
                minIndex = b;
            } 
            // If tail lengths are equal, compare names (secondary criterion)
            else if (currentDog.getTailLength() == minDog.getTailLength()) {
                // Use String.compareTo() for lexicographical name comparison
                if (currentDog.getName().compareTo(minDog.getName()) < 0) {
                    minDog = currentDog;
                    minIndex = b;
                }
            }
        }
        
        // Swap the current element with the found minimum element
        if (minIndex != a) {
            Dog temp = listOfDogs.get(a);
            listOfDogs.set(a, listOfDogs.get(minIndex));
            listOfDogs.set(minIndex, temp);
        }
    }
    return listOfDogs;
}

Key Changes Explained:

  • Instead of tracking separate minValue variables for tail length and name, we track the full Dog object as our minimum. This avoids redundant list lookups and makes comparing both fields cleaner.
  • The inner loop prioritizes tail length first: if a dog has a shorter tail than the current minimum, it becomes the new minimum immediately.
  • When tail lengths are identical, we fall back to comparing names using String.compareTo()—this ensures dogs with the same tail length are sorted alphabetically by name.
  • The swap logic stays exactly like your original code, since we're still just swapping elements once we've found the true minimum for the current position.

This approach maintains the same O(n²) time complexity as your original selection sort methods, but handles both sorting rules in a single pass over the list—more efficient than running two separate sorts back-to-back.

内容的提问来源于stack exchange,提问作者SenorPoppa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:37:52