Home computickets Python 3 Bubble Sort Both Sides

Python 3 Bubble Sort Both Sides

Author

Date

Category

Challenge: Write a function bubble (lst, a = False) that takes one required argument, a list of numbers, sorts the list using the bubble method, and returns the resulting list.

The desc argument specifies the sort order. If it is True, then the function sorts in descending order, if it is False, then it sorts in ascending order.

By default, the function sorts the list in ascending order.

It is forbidden to use the built-in features of the language for sorting.

All you need is the I / O function, no need to implement

Tell me, pzhl, what’s wrong with my version?

def bubble (lst, a = False):
  if a:
   for i in range (len (lst) -1):
    for j in range (len (lst) -i-1):
      if lst [j] & gt; lst [j + 1]:
        lst [j], lst [j + 1] = lst [j + 1], lst [j]
  elif not a:
   for i in range (len (lst) -1):
    for j in range (len (lst) -i-1):
      if lst [j] & lt; lst [j + 1]:
        lst [j], lst [j + 1] = lst [j + 1], lst [j]
 return lst

Answer 1

def bubble (lst, desc = False):
  if (not desc):
    for i in range (len (lst) -1):
      for j in range (len (lst) -i-1):
        if lst [j] & gt; lst [j + 1]:
          lst [j], lst [j + 1] = lst [j + 1], lst [j];
  else:
    for i in range (len (lst) -1):
      for j in range (len (lst) -i-1):
        if lst [j] & lt; lst [j + 1]:
          lst [j], lst [j + 1] = lst [j + 1], lst [j];
  return lst;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions