#### Overview of this book

Choosing the right data structure is pivotal to optimizing the performance and scalability of applications. This new edition of Hands-On Data Structures and Algorithms with Python will expand your understanding of key structures, including stacks, queues, and lists, and also show you how to apply priority queues and heaps in applications. You’ll learn how to analyze and compare Python algorithms, and understand which algorithms should be used for a problem based on running time and computational complexity. You will also become confident organizing your code in a manageable, consistent, and scalable way, which will boost your productivity as a Python developer. By the end of this Python book, you’ll be able to manipulate the most important data structures and algorithms to more efficiently store, organize, and access data in your applications.
Preface
Free Chapter
Python Data Types and Structures
Introduction to Algorithm Design
Algorithm Design Techniques and Strategies
Stacks and Queues
Trees
Heaps and Priority Queues
Hash Tables
Graphs and Algorithms
Searching
Sorting
Selection Algorithms
String Matching Algorithms
Other Books You May Enjoy
Index

# Bubble sort algorithms

The idea behind the bubble sort algorithm is very simple. Given an unordered list, we compare adjacent elements in the list, and after each comparison, we place them in the right order according to their values. So, we swap the adjacent items if they are not in the correct order. This process is repeated `n-1` times for a list of `n` items.

In each iteration, the largest element of the list is moved to the end of the list. After the second iteration, the second largest element will be placed at the second-to-last position in the list. The same process is repeated until the list is sorted.

Let’s take a list with only two elements, {`5`, `2`}, to understand the concept of bubble sort, as shown in Figure 11.1:

Figure 11.1: Example of bubble sort

To sort this list of two elements, first, we compare `5` and `2`; since `5` is greater than `2`, it means they are not in the correct order, so we swap these values to put them in the correct order. To swap...