为什么我的BubbleSearch仅部分生效?技术问题排查请求
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]:
- First pass: Swaps happen at i=0 (4↔2) and i=4 (12↔5), resulting in
[2,4,9,11,5,12].fixedends asfalse, so the loop continues. - Second pass:
- i=0-2: No swaps occur.
- i=3: 11>5, swap to get
[2,4,9,5,11,12], setfixed=false. - i=4: The loop first runs
fixed=true;, then checks 11 vs 12 (no swap). Nowfixedistrueagain.
- Loop exits: Since
fixedistrueafter the second pass, thewhile(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

