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

为什么我的BubbleSearch仅部分生效?技术问题排查请求

Bubble Sort Only Partially Sorts the Array - Here's Why

Let's break down the issue with your bubble sort implementation clearly:

The Root Cause

Your fixed=true; line is placed inside the for loop, meaning it gets reset to true on every single iteration through the array elements. Even if a swap happens earlier in the current pass, the next element comparison will overwrite fixed back to true—tricking your loop into thinking no swaps occurred in the entire pass, and causing it to terminate early.

Walkthrough of Your Example

Take your input array [4, 2, 9, 11, 12, 5]:

  1. First pass: Swaps happen at i=0 (4↔2) and i=4 (12↔5), resulting in [2,4,9,11,5,12]. fixed ends as false, so the loop continues.
  2. Second pass:
    • i=0-2: No swaps occur.
    • i=3: 11>5, swap to get [2,4,9,5,11,12], set fixed=false.
    • i=4: The loop first runs fixed=true;, then checks 11 vs 12 (no swap). Now fixed is true again.
  3. Loop exits: Since fixed is true after the second pass, the while(fixed==false) condition fails, and the sort stops early—leaving the array partially sorted.

The Fix

Move the fixed=true; line outside the for loop, so it only runs once at the start of each full pass through the array. This way, we correctly assume no swaps will happen in the pass, and only set fixed=false if any swap actually occurs.

Here's the corrected code:

public static void bubbleSort(int array[]){ 
    boolean fixed= false; 
    while(fixed==false){ 
        fixed=true;  // Initialize once per pass, not per element
        for(int i=0; i<array.length-1; i++){ 
            int temp; 
            if (array[i] > array[i+1]){ 
                temp= array[i+1]; 
                array[i+1]= array[i]; 
                array[i]= temp; 
                fixed=false; 
            } 
        } 
    } 
}

Bonus Optimization

Bubble sort can be optimized further by reducing the number of elements we check each pass—since each full pass bubbles the largest unsorted element to its correct position at the end of the array. Here's an improved version:

public static void bubbleSort(int array[]){ 
    boolean swapped;
    int endIndex = array.length;
    do {
        swapped = true;
        endIndex--;  // Skip already sorted elements at the end
        for(int i=0; i<endIndex; i++){ 
            if (array[i] > array[i+1]){ 
                // Swap elements
                int temp = array[i];
                array[i] = array[i+1];
                array[i+1] = temp;
                swapped = false; 
            } 
        } 
    } while(!swapped);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:56:59