The Bubble Sort algorithm works by comparing a pair of neighbor elements and shifting the larger of the two to the right. Bubble Sort completes this by swapping the two elements’ positions if the first element being compared is larger than the second element being compared.
Below is a quick pseudocode example of what we will create:
for each pair(elem1, elem2): if elem1 > elem2: swap(elem1, elem2) else: # analyze next set of pairs
swap() sub-routine is an essential part of the algorithm. Bubble sort swaps elements repeatedly until the largest element in the list is placed at the greatest index. This looping continues until the list is sorted.
This GIF illustrates how
swap() method works.
Define the function
swap() which has three parameters:
pass in the body of the function for now.
Create the variable
temp and assign to it the value located at
temp, set the value at
arr to be the value at
Then, set the value located at
index_2 to be
Uncomment the code at the bottom of the file to test out