Page 61 - Touchcode_C8_Flipbook
P. 61
Step 5: Type the following code:
Explanation:
Create a variable ‘i’ (integer) and assign it a value 0.
Create a variable ‘s’ (string).
Create a variable ‘k’ (integer) and assign it a value 0.
Create an array ‘arr1’ and declare its value as [1,6,4,14,2,7,19].
Create a ‘while’ loop, with condition (i<len(arr1)-1) (this loop will run from first
to last element of an array).
Create a variable ‘j’ (integer) and assign it a value 0.
Create a ‘while’ loop, with condition (j <=len(arr1)-1-i) (this loop will run from
first to second last element of an array).
Concept: Bubble sort compares two adjacent elements and swap the smallest
element with the largest.
Inside the function, we have defined two while loop—the first ‘while’ loop
iterates the complete list and the second ‘for’ loop iterates the list and
compare the two elements in every outer loop iterations.
The while loop will be terminated when it reaches the end.
We have defined the condition in the inner while loop; if the value of first
index is greater than the second index value, swap their positions with
each other.
We called the function and passed a list; it iterated and returned the
sorted list.
We are comparing the first element of an array ‘arr1’ with the second
element.
Programming with Arrays 59

