如何仅使用IF和GOTO语句实现一维数组的冒泡排序?
Fixing Bubble Sort with Only IF and GOTO (Fortran)
Hey there! Let's work through your bubble sort implementation—nested loops using just IF and GOTO are totally doable, you just need to align the label flow with bubble sort's core logic and fix a few key issues in your current code.
First, let's break down what's off in your existing code:
- Wrong sorting logic: You're comparing
arr(i)with everyarr(j), which is closer to selection sort, not bubble sort. Bubble sort relies on swapping adjacent elements to "bubble" the largest unsorted value to the end each pass. - Broken swap: Lines 10-12 don't actually swap elements. You overwrite
arr(j)witharr(i)before assigningarr(i)to the modifiedarr(j)—so no change happens. - Inefficient loop bounds: The inner loop should only run through the unsorted portion of the array (up to
arr_size - i), since each outer pass leaves the lastielements sorted. - Misplaced jumps: After modifying
j, you're jumping back to the outer loop check instead of the inner loop, which breaks the nested flow.
Here's a corrected, working version that sticks strictly to your constraints, plus a breakdown of how the nested loops work:
integer i,j,arr_size character*26 arr(1000), tmp c Initialize outer loop counter i = 1 c Outer loop guard: check if we need another pass 299 if(i .lt. arr_size) go to 300 go to 305 ! Exit sorting, all elements are ordered c Start a new outer pass: reset inner loop counter to start of unsorted section 300 j = 1 c Inner loop guard: check if j is within the unsorted range 301 if(j .lt. arr_size - i) go to 302 go to 304 ! End inner pass, move to next outer iteration c Compare adjacent elements: swap if out of order 302 if(arr(j) .gt. arr(j+1)) go to 303 go to 306 ! No swap needed, move to next pair 303 tmp = arr(j) arr(j) = arr(j+1) arr(j+1) = tmp ! Correct swap logic using temporary variable c Increment inner loop counter and jump back to inner guard 306 j = j + 1 go to 301 c Increment outer loop counter and jump back to outer guard 304 i = i + 1 go to 299 c Exit point for the subroutine 305 return end
How the Nested Loops Work with IF/GOTO:
- Outer loop: Label
299acts as the loop condition check. Whenireachesarr_size, we exit to305(sorting complete). After each inner loop finishes, we incrementiat304and jump back to299to start the next pass. - Inner loop: For each outer pass, we reset
jto 1 at300. Label301checks if we're still in the unsorted part of the array. After each comparison (swap or not), we incrementjand jump back to301to check the next adjacent pair. - Swap correction: We now use
tmpto store the original value ofarr(j)before overwriting it witharr(j+1), then assigntmptoarr(j+1)—this properly swaps the two elements.
This structure exactly mimics the nested DO loops you'd use in modern Fortran, but uses only IF and GOTO for flow control, matching your requirements.
内容的提问来源于stack exchange,提问作者Huzo
相关产品推荐
相关产品推荐

