Monday, 16 July 2018

Bubble Sort Using Excel VBA

For I = 1 To 5
   Small = Cells(I, 1)
   For J = I+1 To 5
      If Small > Cells(J, 1) Then
      Temp = Small
      Small = Cells(J, 1)
      Cells(J, 1) = Temp
      Cells(I, 1) = Small
   End If
   Next J
Next I

*Place 5 unsorted data in A1 to A5.  You can copy and paste the "Original Data" from Column C1 to C5 and paste it at cell A1.

The program starts off with the first loop by assuming the smallest number is A1 which is 5 (assuming the data is not sorted yet).  Small is the variable used to store that value.  Then the next loop is entered where Small is checked against the rest of list.  If the somehow [ If Small > Cells(J,1) ], the Assumed Smallest value is incorrect, then a swap is made. 

Small is stored into the variable Temp [ Temp = Small ].  The variable Small  now has a newer value which is definitely smaller than the previously assumed one [ Small = Cells(J,1) ].  Then the location where the smaller value was found will be replaced with the former value [ Cells(J,1) = Temp ].  Finally, the place where formerly the location where the Assume Smallest value was thought it would be is placed with the newer Smaller value [Cells(I,1) = Small].


No comments:

Post a Comment