Algorithm _ bubble program, algorithm bubble Program
There is nothing to say about the first algorithm here. It must start with the most classic bubble algorithm and list python and c versions.
The bubble algorithm is very simple, just like the bubble algorithm. It can also be understood as light and float from below.
For example, there is a list = [3, 2, 5, 4, 1], first 3 and 2 ratio, 2 light, 2 float, 3 sink, 3 and 5 ratio, 3 light, position unchanged, 5 to 4 ratio, 4 floating up, 5 to 1 ratio, 1 floating up
After the first comparison, we get [2, 3, 4, 1, 5] And then perform the second and third operations until the final result is completed, generally, the version of this algorithm is a nested loop, that is, for. It seems that it has fallen into this loop, but it doesn't need to be all the same. If the initial list is [, 5], in fact, we can get the result for the first time. Isn't it useless?
Okay, I don't have much gossip. It's a great blessing to go to the Code, chat, tea, and code.
Pseudocode
Sequence = [3, 2, 5, 4, 1] indicates the initialization of the cyclic sequence, and ends the loop until the mark does not change. If the first> second, second, and first positions change, the mark value changes, the record changes back to the header and recyclically
Python version
#! /Usr/bin/python # coding: UTF-8def bubble_sort (num_list): num_len = len (num_list) while True: n = 0 ''' range here-1 is because the following + 1, if the value is not-1, an out of range error will be reported after + 1, and the algorithm can query len (list)-1 times at most, so this is okay ''' for I in range (num_len-1): if num_list [I]> num_list [I + 1]: num_list [I], num_list [I + 1] = num_list [I + 1], num_list [I] # switch position n + = 1 if n = 0: break return num_listif _ name _ = '_ main _': num_list = [3, 2, 5, 4, 1] print num_list = bubble_sort (num_list) print num_list
C
# Include <stdio. h> int main () {int num [] = {3, 2, 5, 4, 1}; int I, num_len1; num_len1 = sizeof (num)/4; // The sizeof result is 20. I don't know how to calculate it. It doesn't mean that a number occupies 1bit $ bubble_sort (num, num_len1); for (I = 0; I <num_len1; I ++) {printf ("% d \ n", num [I]);} return 0;} int bubble_sort (int num_list [], int num_len) {int I; while (1) {int n = 0; for (I = 0; I <(num_len-1); I ++) {if (num_list [I]> num_list [I + 1]) {int temp = num_list [I]; num_list [I] = num_list [I + 1]; num_list [I + 1] = temp; n ++ ;}} if (n = 0) {break ;}} return 0 ;}
I have to say that c is really difficult to adapt, but it will always adapt.