livepython.net

226. Python Program to Sort a List with Bubble Sort

HardPhase 3 · Challenge

This one takes a few steps. It uses a while loop, a for loop over positions and swapping with a, b = b, a. You know all of them. Try a short example on paper first.

Overview

Bubble sort is the first way to sort a list that many programmers learn, and interviewers like to ask for it. The big numbers move to the end step by step, like bubbles rising in water.

Problem Statement

Arjun wants to show a class how bubble sort works. Arjun prints the list after each pass, so everyone can watch the numbers move.

The rules:

  • A pass goes through the list from left to right. It compares each pair of neighbours: the numbers at index 0 and 1, then at 1 and 2, and so on, up to the last pair.
  • If the left number of a pair is bigger than the right one, swap them: they change places. Equal numbers are not swapped.
  • After each pass, print the list.
  • Stop after a pass that makes no swap. Print that pass too: it shows that the list is sorted.

Do not use sort() or sorted(): the task is to write the sorting yourself.

Print each pass as Pass <n>: <numbers>, with one space between the numbers. The passes are counted from 1.

Examples

Example 1. Input 5 1 4 2 8 gives:

Pass 1: 1 4 2 5 8
Pass 2: 1 2 4 5 8
Pass 3: 1 2 4 5 8

Why: pass 1 swaps 5 and 1, then 5 and 4, then 5 and 2. Pass 2 swaps 4 and 2. Pass 3 makes no swap, so the sort stops after it.

Example 2. Input 1 2 3 gives:

Pass 1: 1 2 3

Why: the list is already sorted. Pass 1 makes no swap, so it is the only pass.

Input

One line of whole numbers, with one space between them (1 number or more). The numbers can be negative. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line for each pass: Pass, the pass number and a colon, then the numbers, with one space between the parts. The tests try 8 different inputs, also one number, equal numbers and a list from big to small.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Pass 1: 1 4 2 5 8
2Pass 2: 1 2 4 5 8
3Pass 3: 1 2 4 5 8

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.