简体   繁体   中英

Bubble Sort using only IF and GOTO

So I want to implement bubble sort on a 1D array with some restrictions. I should only use IF and GOTO [Label number] in addition to assignment statements and comparisons. In other words, I can only use IF and GOTO to do looping. Normally, I do not find it hard to emulate loops using GOTO and IF but when it is a nested loop, I could not find the correct way. This is my work so far, for reference

  0       integer i,j,arr_size
  1       character*26 arr(1000), tmp
  2       i = 1
  3       j = 1
  4  299  if(i<arr_size) go to 300
  5       go to 305
  6  300  if(j<arr_size) go to 301
  7       go to 304
  8  301  if(arr(i) .gt. arr(j)) go to 302
  9       go to 303
 10  302  tmp = arr(j)
 11       arr(j) = arr(i)
 12       arr(i) = arr(j)
 13       j = j + 1
 14       go to 299
 15  303  j = j + 1
 16       go to 300
 17  304  j = 1
 18       i = i + 1
 19       go to 299
 20  305  return
 21       end

Any ideas?
Thanks!

I think that you code is more a form of selection sort than genuine bubble sort. while your algorithm writes min element at the start of the array, bubble sort is supposed to swap adjacent elements,

Besides the problem already spotted (line 12), at the end of first loop, min element will be at position 1 and the inner loop can start with j=2. So line 17 can be j=i+1 for a small optimization.

Here is an implementation of bubble sort. I have reversed the tests to reduce the number of labels and I use symbolic labels to get cleaner code .

             integer i,j,arr_size
             character*26 arr(1000), tmp
             i = 1
  startouter if(i>=arr_size) go to endouter
             j=1
  startinner if(j>=arr_size) go to endinner
             if(arr(j) .le. arr(j+1)) go to noswap
             tmp = arr(j)
             arr(j) = arr(j+1)
             arr(j+1) = tmp
  noswap     j = j + 1
             go to startinner
  endinner   i = i + 1
             go to startouter
  endouter   return
             end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM