Computer Science

Python Bubble Sort

Python Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. It has a time complexity of O(n^2).

Written by Perlego with AI-assistance

7 Key excerpts on "Python Bubble Sort"

  • 50 Algorithms Every Programmer Should Know
    eBook - ePub

    50 Algorithms Every Programmer Should Know

    An unbeatable arsenal of algorithmic solutions for real-world problems

    The ability to efficiently sort and search items in a complex data structure is important as it is needed by many modern algorithms. The right strategy to sort and search data will depend on the size and type of the data, as discussed in this chapter. While the end result is exactly the same, the right sorting and searching algorithm will be needed for an efficient solution to a real-world problem. Thus, carefully analyzing the performance of these algorithms is important.
    Sorting algorithms are used extensively in distributed data storage systems such as modern NoSQL databases that enable cluster and cloud computing architectures. In such data storage systems, data elements need to be regularly sorted and stored so that they can be retrieved efficiently.
    The following sorting algorithms are presented in this chapter:
    • Bubble sort
    • Merge sort
    • Insertion sort
    • Shell sort
    • Selection sort
    But before we look into these algorithms, let us first discuss the variable-swapping technique in Python that we will be using in the code presented in this chapter.

    Swapping variables in Python

    When implementing sorting and searching algorithms, we need to swap the values of two variables. In Python, there is a standard way to swap two variables, which is as follows:
    var_1 = 1 var_2 = 2 var_1, var_2 = var_2, var_1 print (var_1,var_2)
    2, 1 This simple way of swapping values is used throughout the sorting and searching algorithms in this chapter. Let’s start by looking at the bubble sort algorithm in the next section.

    Bubble sort

    Bubble sort is one of the simplest and slowest algorithms used for sorting. It is designed in such a way that the highest value in a list of data bubbles makes its way to the top as the algorithm loops through iterations. Bubble sort requires little runtime memory to run because all the ordering occurs within the original data structure. No new data structures are needed as temporary buffers. But its worst-case performance is O(N2) , which is quadratic time complexity (where N is the number of elements being sorted). As discussed in the following section, it is recommended to be used only for smaller datasets. Actual recommended limits for the size of the data for the use of bubble sort for sorting will depend on the memory and the processing resources available but keeping the number of elements (N
  • Hands-On Data Structures and Algorithms with Python

    11

    Sorting

    Sorting means reorganizing data in such a way that it is in ascending or descending order. Sorting is one of the most important algorithms in computer science and is widely used in database-related algorithms. For several applications, if the data is sorted, it can efficiently be retrieved, for example, if it is a collection of names, telephone numbers, or items on a simple to-do list.
    In this chapter, we’ll study some of the most important and popular sorting techniques, including the following:
    • Bubble sort
    • Insertion sort
    • Selection sort
    • Quicksort
    • Timsort

    Technical requirements

    All source code used to explain the concepts of this chapter is provided in the GitHub repository at the following link: https://github.com/PacktPublishing/Hands-On-Data-Structures-and-Algorithms-with-Python-Third-Edition/tree/main/Chapter11

    Sorting algorithms

    Sorting means arranging all the items in a list in ascending or descending order. We can compare different sorting algorithms by how much time and memory space is required to use them.
    The time taken by an algorithm changes depending on the input size. Moreover, some algorithms are relatively easy to implement, but may perform poorly with respect to time and space complexity, whereas other algorithms are slightly more complex to implement, but can perform well when sorting longer lists of data. One of the sorting algorithm, merge sort, we have already discussed in Chapter 3 , Algorithm Design Techniques and Strategies . We will discuss several more sorting algorithms one by one in detail along with their implementation details, starting with the bubble sort algorithm.

    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
  • Machine Learning for Decision Sciences with Case Studies in Python
    • S. Sumathi, Suresh Rajappa, L Ashok Kumar, Surekha Paneerselvam(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    Consider an array arr[] with n elements. Let i be the index pointing to the elements in the array. For each element in the array, a comparison is made between arr[ i ] and arr[ i +1]. If arr[ i ] is greater than arr[ i +1], then the elements are swapped, else kept in place. The process is repeated, and each pair of the array arr is compared until the whole array is completely sorted. FIGURE 2.16 Bubble sort. 2.4.5.11 Implementation of Bubble Sort in Python defbubbleSort(mylist): forpassnum in range(len(mylist)-1,0,-1): for i in range(passnum): ifmylist[i]>mylist[i+1]: temp = mylist[i] mylist[i] = mylist[i+1] mylist[i+1] = temp mylist = [1, 2, 3, 5, 47, 31, 13, 17, 19, 23, 29, 11, 37, 31, 47] # sameple list to get it bubble sorted print('the original list:', mylist) # Before sort bubbleSort(mylist) print('the sorted list:', mylist) # After sort Testing the results the original list: [1, 2, 3, 5, 47, 31, 13, 17, 19, 23, 29, 11, 37, 31, 47] the sorted list: [1, 2, 3, 5, 11, 13, 17, 19, 23, 29, 31, 31, 37, 47, 47] 2.4.5.12 Insertion Sort The insertion sort algorithm is a type of in-place sorting algorithm, which in turn is based on the comparison. In this algorithm, a sub-array is maintained, and this sub-array is sorted continuously. Successive elements of the array are added or inserted into this sub-array and sorted within the sub-array. Hence, the name insertion sort. Sometimes, the algorithm is referred to as an online algorithm since the values are sorted and added into the sub-array. The insertion sort algorithm is simple to implement, and it is efficient on small datasets. This comparison sort builds a sorted array by adding one element at a time. The algorithms are explained with a flowchart, as shown in Figure 2.17. Consider an array arr[] whose length is n. The first element of the array is used to form the sub-array, and its position is noted. The next element is chosen for comparison with the first element
  • The Self-Taught Computer Scientist
    eBook - ePub

    The Self-Taught Computer Scientist

    The Beginner's Guide to Data Structures & Algorithms

    • Cory Althoff(Author)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    len function, which will sort a list of strings by length:
    a_list = ["onehundred", "five", "seventy", "two"] print(sorted(a_list, key=len)) >> ['two', 'five', 'seventy', 'onehundred']
    Python's other function for sorting is sort , which has the same optional parameters as sorted , but unlike sorted , sort works only on lists. Also, unlike sorted , sort sorts in place: it changes the original list instead of returning a new one. Here is an example of using sort on a list:
    a_list = [1, 8, 10, 33, 4, 103] a_list.sort() print(a_list) >> [1, 4, 8, 10, 33, 103]
    As you can see, Python sorted the numbers in your original list in ascending order.

    Vocabulary

    • sorting data: Arranging data in a meaningful way.
    • bubble sort: A sorting algorithm where you iterate through a list of numbers, compare each number with the next number, and swap them if they are out of order.
    • stable sort: A sort that does not disturb any sequences other than the one specified by the sort key.
    • insertion sort: A sorting algorithm where you sort data like you sort a deck of cards.
    • merge sort: A recursive sorting algorithm that continually splits a list in half until there are one or more lists containing one item, and then puts them back together in the correct order.
    • divide-and-conquer algorithm: An algorithm that recursively breaks a problem into two or more related subproblems until they are simple enough to solve easily.
    • hybrid sorting algorithm: An algorithm that combines two or more other algorithms that solve the same problem, either choosing one (depending on the data) or switching between them throughout the algorithm.

    Challenge

    1. Research and write a sorting algorithm that is not a bubble sort, insertion sort, or merge sort.
    Passage contains an image

    5 String Algorithms

    One of the most important skills any entrepreneur should learn is to program a computer. This is a critical skill if you want to start a tech startup, but a basic knowledge of code is useful even in traditional fields, because software is changing everything.
  • Handbook of Computer Programming with Python
    • Dimitrios Xanthidis, Christos Manolas, Ourania K. Xanthidou, Han-I Wang(Authors)
    • 2022(Publication Date)
    th pass Comparisons are made with no swaps A Python implementation of a basic bubble sort and its output is provided below:
    1 # Import the random module to generate random numbers 2 import random 3 import time 4 5 comparisons = 0 6 list = [] 7 8 # Enter the number of list elements 9 size = int(input("Enter the number of list elements: ")) 10 # Use the randint() function to generate random integers 11 for i in range (size): 12 newNum = random.randint(-100, 100) 13 list.append(newNum) 14 print("The unsorted list is: ", list) 15 16 # Bubble sorts the list & records the stats for later use 17 # Start the timer 18 startTime = time.process_time() 19 20 # The bubble sort algorithm 21 for i in range (size-1): 22 for j in range (size-1): 23 comparisons += 1 24 if (list[j] > list[j+1]): 25 temp = list[j] 26 list[j] = list[j+1] 27 list[j+1] = temp 28 29 # End the timer 30 endTime = time.process_time() 31 32 # Display the basic info for the bubble sort 33 print("The sorted list is: ", list) 34 print("The number of comparisons is: ", comparisons) 35 print("The elapsed time in seconds is: ", (endTime - startTime))
    Output 6.3.1:
    Enter the number of elements in the list:7 The unsorted list is: [33, -16, -57, -17, 95, 5, 15] The sorted list is: [-57, -17, -16, 5, 15, 33, 95] The number of comparisons is = 36 The elapsed time in seconds = 0.0

    6.3.2 Insertion Sort

    Insertion sort is another basic sorting algorithm, similar to bubble sort but somewhat improved. The basic idea is that on the ith pass the algorithm inserts the ith element into the appropriate place (i.e., L[i]) at the end of the L[1], L[2], , L[i-1] sequence, the elements of which have been previously placed in sorted order. As a result, after the insertion, the elements occupying the L[1], L[2], , L[i]
  • Hands-On Data Structures and Algorithms with Python
    eBook - ePub

    Hands-On Data Structures and Algorithms with Python

    Write complex and powerful code using the latest features of Python 3.7, 2nd Edition

    • Dr. Basant Agarwal, Benjamin Baka(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)

    Sorting

    Sorting means reorganizing the data in such as way that it is in the order of smallest to largest. Sorting is one of the most important issues in data structures and computing. Data is regularly sorted before being sorted, as it can then very efficiently be retrieved, be it a collection of names, telephone numbers, or items on a simple to-do list.
    In this chapter, we'll study some of the most important and popular sorting techniques, including the following:
    • Bubble sort
    • Insertion sort
    • Selection sort
    • Quick sort
    • Heap sort
    In this chapter, we compare different sorting algorithms by considering their asymptotic behavior. Some of the algorithms are relatively easy to develop, but may perform poorly, whereas other algorithms are slightly more complex to implement, but show good performance in sorting the list when we have a long lists.
    After sorting, it becomes much easier to conduct search operations on a collection of items. We'll start with the simplest of all sorting algorithms; that is, the bubble sort algorithm.
    Passage contains an image

    Technical requirements

    All source code used to explain the concepts of this chapter is provided in the GitHub repository at the following link: https://github.com/PacktPublishing/Hands-On-Data-Structures-and-Algorithms-with-Python-Second-Edition/tree/master/Chapter10 .
    Passage contains an image

    Sorting algorithms

    Sorting means arranging all the items in a list in ascending order of their magnitude. We will be discussing some of the most important sorting algorithms, which each have different performance attributes with respect to runtime complexity. Sorting algorithms are categorized by their memory usage, complexity, recursion, and whether they are comparison-based, among other considerations.
    Some of the algorithms use more CPU cycles, and, as such, have bad asymptotic values. Other algorithms chew on more memory and other computing resources as they sort a number of values. Another consideration is how sorting algorithms lend themselves to being expressed recursively, iteratively, or both. There are algorithms that use comparison as the basis for sorting elements. An example of this is the bubble sort algorithm. Examples of a non-comparison sorting algorithm are the bucket sort and pigeonhole sort algorithms.
  • An Introduction to Python Programming: A Practical Approach
    eBook - ePub

    An Introduction to Python Programming: A Practical Approach

    step-by-step approach to Python programming with machine learning fundamental and theoretical principles.

    • Dr. Krishna Kumar Mohbey; Dr. Brijesh Bakariya(Author)
    • 2021(Publication Date)
    • BPB Publications
      (Publisher)
    In-place sorting : In this sorting technique, the elements are sorted within a list. There is no extra space required for sorting an element.
  • Not-in-place sorting : In this sorting technique, the elements are sorted, but a different list is required. There is extra space needed for sorting elements.
  • Stable sorting : In a sorting algorithm, stable sorting occurs when the contents do not change the sequence of related content in which they appear after sorting.
  • Unstable sorting : After sorting, if the contents change the sequence of similar content in which they appear, it is called unstable sorting in a sorting algorithm.
  • Bubble sort

    Bubble sort is a comparison-based algorithm that compares each pair of adjacent elements and swaps them if they are out of order. Since the average and worst-case complexity of this algorithm are O(n2), where n is the number of items, it is not suitable for large data sets. The bubble sorting procedure is as follows. To begin with, we'll make a list of an element that will hold the integer numbers.
    list1 = [5, 3, 8, 6, 7, 2] There are following iterations for sorting. First iteration [5, 3, 8, 6, 7, 2] It compares the first two elements and here 5>3 then swap with each other. Now we get a new list that is [3, 5, 8, 6, 7, 2] In the second comparison, 5 < 8, then swapping will happen [3, 5, 8, 6, 7, 2] In the third comparison, 8>6, then swap [3, 5, 6, 8, 7, 2] In the fourth comparison, 8>7, then swap [3, 5, 6, 7, 8, 2] In the fifth comparison, 8>2, then swap [3, 5, 6, 7, 2, 8]
    Here, the first iteration is complete and we get the largest element at the end. Now we need to the len(list1) – 1
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.