Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 55 Online
OpenStudy (noah):

Bubble sort

OpenStudy (heisenberg):

What would you like to know about it? It is one of the most basic sorting algorithms. Not the best, but not too bad for short lists.

OpenStudy (noah):

can you give example? I have array [9, 2, 5, 4]

OpenStudy (heisenberg):

The basic logic behind bubble sort is that you start with the first element and "sweep" it through the array, swapping it with its neighbor if it is out of order. in your example it would be as follows:

OpenStudy (heisenberg):

[9, 2, 5, 4] <- here we choose 9 and compare it to 2. 9 > 2 so we swap them and continue [2, 9, 5, 4] <- now 9 > its neighbor, 5 so we swap [2, 5, 9, 4] <-one more time [2, 5, 4, 9] <- now that we've reached the end we start over at the element that directly follows the one we chose this previous time. in this case, since we started on the 1st element (then a 9), we start on the 2nd element in the array, 5. since 5 > 4, we swap. [2, 4, 5, 9] <- 5 is not > 9, so we don't swap here. you can see we are now sorted, but the algorithm may continue on, checking the 3rd element (5) with the 4th (9). since 5 is not > 9, we do not swap. we have then reached our final element. so we know for sure it is in sorted order.

OpenStudy (noah):

thank you

OpenStudy (heisenberg):

Please fan me if I helped. :)

OpenStudy (anonymous):

A good way to get an idea of how these functions work is to just build one based on the description. Here is one that I made as an example: # Bubble Sort def check(a): for n in range(1,len(a)): if a[n] < a[n-1]: return True return False def bubble(a): b = a[:] while check(b) == True: for n in range(1,len(b)): c = b[:] if b[n] < b[n-1]: b[n] = c[n-1] b[n-1] = c[n] return b

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!