Home > Backend Development > Python Tutorial > Bubble Search... Swap (x, y);

Bubble Search... Swap (x, y);

Susan Sarandon
Release: 2024-12-07 08:17:12
Original
407 people have browsed it

Bubble Search

Bubble search is one of the most common and basic sorting technique which is used to sort an array. Most common parameters are array which is to be sorted and a size of an array (optional).

Technique used in Bubble Sort
In bubble sort, sorting happens based on comparison between two element, like which one is greater or lesser.

Bubble Search... Swap (x, y);

Eg:

list = [2, 1]
if list[0] > list[1]:
  list[0], list[1] = list[1], list[0]
Copy after login
  • Above the list become [1, 2]. Here we compare 0th and 1th index, if the 0th index value is greater than 1th index value then the swapping will happen.
  • This process will be applied to all the elements in an array until the array is sorted.
  • We need to apply this process iteratively to sort an array of N size.

Implementation of Bubble Sort!

def bubble_sort (array: list) -> list:
  for i in range(0, len(array) - 1):
    for j in range(0, len(array) - 1 - i):
      if array[j] > array[j + 1]:
        array[j], array[j+1] = array[j+1], array[j]

  return arr
Copy after login
  • The outer loop will be run for N time to move all the at it correct position. The outer loop act as pass which is mentioned in the above image.
  • The inner loop will make comparison between current and next elements, if the condition meet then the swap will happen.

Time complexity is O(N^2)

print(Happy Coding)

The above is the detailed content of Bubble Search... Swap (x, y);. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template