[Sorting] Bubble Sort (Full Implementation/C++)

Changjin
Feb 10, 2021

--

Hello! Today, we’ll be looking at bubble sort. Bubble sort is a sorting algorithm that behaves like “bubbles” and takes O(n²) time complexity. The key point of bubble sort is that “For each iteration, we drag the greatest element to the end(decrement by 1 each time) by each consecutive pair”. Let’s take an example.

  1. [5,3,1] -> [3,5,1] -> [3,1,5]
  2. [3,1,5] -> [1,3,5]

Notice that for each iteration, the last element is replaced by the greatest element. Therefore, decrement the searching range of the array by 1 for each iteration.

A slight optimization can be done. If nothing happens for an iteration, then it means the array is already sorted so pause it.

Implementation

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Changjin
Changjin

No responses yet

Write a response