Computer Science

Bubble Sort

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 pass through the list is repeated until the list is sorted. It is not efficient for large lists and is mainly used for educational purposes.

Written by Perlego with AI-assistance

10 Key excerpts on "Bubble Sort"

  • 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)
    The same principle is used even if the list contains many elements. There are a lot of variations of the Bubble Sort, too, that minimize the number of iterations and comparisons.
    For example, t
    here is a variant of the Bubble Sort algorithm where, if there is no swapping within the inner loop, we simply quit the entire sorting process, because the absence of any swapping operation in the inner loop suggests that the list has already been sorted. In a way, this can help speed up the algorithm.
    The Bubble Sort is an inefficient sorting algorithm that provides worst-case and average-case runtime complexity of O(n2 ), and a best-case complexity of O(n). Generally, the Bubble Sort algorithm should not be used to sort large lists. However, on relatively small lists, it performs fairly well.
    Passage contains an image

    Insertion sort algorithms

    The idea of swapping adjacent elements to sort a list of items can also be used to implement the insertion sort. An insertion sorting algorithm maintains a sub-list that is always sorted, while the other portion of the list remains unsorted. We take elements from the unsorted sub-list and insert them in the correct position in the sorted sub-list, in such a way that this sub-list remains sorted.
    In insertion sorting, we start with one element, assuming it to be sorted, and then take another element from the unsorted sub-list and place it at the correct position (in relation to the first element) in the sorted sub-list. This means that our sorted sub-list now has two elements. Then, we again take another element from the unsorted sub-list, and place it in the correct position (in relation to the two already sorted elements) in the sorted sub-list. We repeatedly follow this process to insert all the elements one by one from the unsorted sub-list into the sorted sub-list. The shaded elements denote the ordered sub-lists, and in each iteration, an element from the unordered sub-list is inserted at the correct position in the sorted sub-list.
    Let's consider an example to understand the working of the insertion sorting algorithm. In our example, we'll be sorting a list of 6 elements: {45, 23, 87, 12, 32, 4}. Firstly, we start with 1 element, assuming it to be sorted, then take the next element, 23, from the unsorted sub-list and insert it at the correct position in the sorted sub-list. In the next iteration, we take the third element, 87, from the unsorted sub-list, and again insert it into the sorted sub-list at the correct position. We follow the same process until all elements are in the sorted sub-list. This whole process is shown in the following diagram:
  • Essential Algorithms
    eBook - ePub

    Essential Algorithms

    A Practical Approach to Computer Algorithms Using Python and C#

    • Rod Stephens(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    Like insertionsort, selectionsort is fast enough for reasonably small arrays (fewer than 10,000 or so items). It's also a fairly simple algorithm, so it may sometimes be faster than more complicated algorithms for very small arrays (typically 5 to 10 items).

    Bubblesort

    Bubblesort uses the fairly obvious fact that if an array is not sorted, then it must contain two adjacent elements that are out of order. The algorithm repeatedly passes through the array, swapping items that are out of order, until it can't find any more swaps.
    The following pseudocode shows the bubblesort algorithm:
    Bubblesort(Data: values[]) // Repeat until the array is sorted. Boolean: not_sorted = True While (not_sorted) // Assume we won't find a pair to swap. not_sorted = False // Search the array for adjacent items that are out of order. For i = 0 To <length of values> - 1 // See if items i and i - 1 are out of order. If (values[i] < values[i - 1]) Then // Swap them. Data: temp = values[i] values[i] = values[i - 1] values[i - 1] = temp // The array isn't sorted after all. not_sorted = True End If Next i End While End Bubblesort
    The code uses a Boolean variable named not_sorted to keep track of whether it has found a swap in its most recent pass through the array. As long as not_sorted is true, the algorithm loops through the array, looking for adjacent pairs of items that are out of order and swaps them.
    Figure 6.3
  • 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
  • Beginning Java Data Structures and Algorithms
    eBook - ePub

    Beginning Java Data Structures and Algorithms

    Sharpen your problem solving skills by learning core computer science concepts in a pain-free manner

    Sorting Algorithms and Fundamental Data Structures

    In the previous chapter, we saw how the intersection problem can be improved by using a sorting algorithm. This is common with many problems. If the data is organized in an ordered manner, a more efficient algorithm can be developed. In this chapter, we will start by exploring three types of sorting techniques, which are bubble, quick, and merge sorting. Later, we will learn different ways to organize data using fundamental data structures.
    By the end of this chapter, you will be able to:
    • Describe how Bubble Sorting works
    • Implement faster sorting with quick sort
    • Characterize merge sorting
    • Build a linked list data structure
    • Implement queues
    • Describe the stack data structure
    Passage contains an image

    Introducing Bubble Sorting

    Bubble Sorting is the simplest sorting algorithm out there. The technique involves making multiple passes over the input array and swapping unordered elements close to one another. The technique is called Bubble Sort, as the sorted list "bubbles" up from the tail end of the list.
    Passage contains an image

    Understanding Bubble Sorting

    All sorting algorithms accept a list of elements and return them ordered. The main difference between each algorithm is the manner in which the sorting is done. Bubble Sorting works by swapping adjacent elements. This pushes the sorted elements toward the end of the list.
    Snippet 2.1 shows the pseudocode for Bubble Sort. The algorithm involves three simple tasks, which involves repeatedly stepping through the list to sort, comparing adjacent elements, and swapping them around if the first element is bigger than the second.
    How many passes do we need to perform on the array until our list is sorted? It turns out that to guarantee that our list is sorted, we need to do (n - 1) passes on the list, n being the length of our array. We will show why (n - 1) passes are needed in the next section, but this is the main reason why Bubble Sort has a runtime complexity of
    O(n2 )
    , since we're processing n elements for n - 1
  • PHP 7 Data Structures and Algorithms
    Sorting can be classified into different types based on the type of data set, direction, computational complexities, memory usage, space usage, and so on. Here are few of the sorting algorithms we will explore in this chapter:
    • Bubble Sort
    • Insertion sort
    • Selection sort
    • Quick sort
    • Merge sort
    • Bucket sort
    We will keep our discussion limited to the preceding list, as they are the most commonly used sorting algorithms and can be grouped and classified under different criteria such as simple sorting, efficient sorting, distribution sorting, and so on. We will now explore each of the sorting functionalities, their implementations, and complexity analysis, along with their pros and cons. Let's get started with the most commonly used sorting algorithm - Bubble Sort.
    Passage contains an image

    Understanding Bubble Sort

    Bubble Sort is the most commonly used sorting algorithm in the programming world. Most of the programmers start learning about sorting with this algorithm. It is a comparison-based sorting algorithm, which is always referred to as one of the most inefficient sorting algorithms. It requires maximum number of comparisons, and the average, and worst case complexity are the same.
    In Bubble Sort, each item of the list is compared with the rest of the items and swapped if required. This continues for each item in the list. We can sort either in ascending or descending order. Here is the pseudo algorithm for Bubble Sort:
    procedure bubbleSort( A : list of sortable items ) n = length(A) for i = 0 to n inclusive do for j = 0 to n-1 inclusive do if A[j] > A[j+1] then swap( A[j], A[j+1] ) end if end for end for end procedure
    As we can see from the preceding pseudocode, we are running one loop to ensure that we iterate each item of the list. The inner loop ensures that, once we point to an item, we are comparing the item with other items in the list. Based on our preference, we can swap the two items. The following image shows a single iteration to sort one item of the list. Let's assume our list has the following items: 20 , 45 , 93 , 67 , 10 , 97 , 52 , 88 , 33 , 92
  • 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
  • Learning JavaScript Data Structures and Algorithms
    When developers start learning sorting algorithms, they usually learn the Bubble Sort algorithm first, because it is the simplest of all the sorting algorithms. However, it is one of the worst-case sorting algorithms with respect to runtime, and you will see why.
    The Bubble Sort algorithm compares every two adjacent values and swaps them if the first one is bigger than the second one. It has this name because the values tend to move up into the correct order, like bubbles rising to the surface.
    Let's implement the Bubble Sort algorithm, as follows:
    function bubbleSort(array, compareFn = defaultCompare) { const { length } = array; // {1} for (let i = 0; i < length; i++) { // {2} for (let j = 0; j < length - 1; j++) { // {3} if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) { // {4} swap(array, j, j + 1); // {5} } } } return array;}
    Each non-distribution sort algorithm we will create in this chapter will receive the array to be sorted  as a parameter and a comparison function. To make testing easier to understand, we will work with arrays of numbers in our examples. But in case we need to sort an array of complex objects (array of people objects sorted by age property), our algorithm will be ready as well. The compareFn function to be used as default is the defaultCompare function we have used in previous chapters (return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN).
    First, let's declare a variable called length, which will store the size of the array ({1}). This step will help us to get the size of the array on lines {2} and {3}, and this step is optional. Next, we will have an outer loop ({2}) that will iterate the array from its first position to the last one, controlling how many passes are done in the array (which should be one pass per item of the array as the number of passes is equal to the size of the array). Then, we have an inner loop ({3}) that will iterate the array, starting from its first position to the penultimate value that will actually do the comparison between the current value and the next one ({4}). If the values are out of order (that is, the current value is bigger than the next one), then we will swap them ({5}), meaning that the value of the j+1 position will be transferred to the j position and vice versa.
  • The Complete Coding Interview Guide in Java
    eBook - ePub

    The Complete Coding Interview Guide in Java

    An effective guide for aspiring Java developers to ace their programming interviews

    Java Coding Problems , you can find detailed coverage of Bubble Sort, Insertion Sort, Counting Sort, and so on.
    Furthermore, the application called SortArraysIn14Ways contains the implementations of 14 different sorting algorithms that you should know. The complete list is as follows:
    • Bubble Sort
    • Bubble Sort with a Comparator
    • Bubble Sort optimized
    • Bubble Sort optimized with a Comparator
    • Pancake Sort
    • Exchange Sort
    • Selection Sort
    • Shell Sort
    • Insertion Sort
    • Insertion Sort with a Comparator
    • Counting Sort
    • Merge Sort
    • Heap Sort
    • Heap Sort with a Comparator
    • Bucket Sort
    • Cocktail Sort
    • Cycle Sort
    • Quick Sort
    • Quick Sort with a Comparator
    • Radix Sort
    In the following sections, we will have a brief overview of the main algorithms that are encountered in interviews: Heap Sort, Merge Sort, Quick Sort, Bucket Sort, and Radix Sort. If you are already familiar with these algorithms, then consider jumping directly to the Searching algorithms section, or even to the Coding challenges section.

    Heap Sort

    If you are not familiar with the heap concept, then consider reading the Binary Heaps section of Chapter 13 , Trees and Graphs .
    Heap Sort is an algorithm that relies on a binary heap (a complete binary tree). The time complexity cases are as follows: best case O(n log n), average case O(n log n), worst case O(n log n). The space complexity case is O(1).
    Sorting elements in ascending order can be accomplished via a Max Heap (the parent node is always greater than or equal to the child nodes), and in descending order via a Min Heap (the parent node is always smaller than or equal to the child nodes).
    The Heap Sort algorithm has several main steps, as follows:
    1. Transform the given array into a Max Binary Heap.
    2. Next, the root is swapped with the last element from the heap and the heap's size is reduced by 1 (this is like deleting the root element of the heap). So, the greater element (the heap root) goes to the last position. In other words, the elements that are at the root of the heap come out one by one in sorted order.
  • C++ Data Structures and Algorithms

    Arranging Data Elements Using a Sorting Algorithm

    In the previous chapter, we discussed several linear data structures, such as linked list, stack, queue, and dequeue. In this chapter, we are going to arrange data elements in a list using some sorting algorithm techniques. The following are the popular sorting algorithms that we are going to discuss in this chapter:
    • Bubble Sort
    • Selection sort
    • Insertion sort
    • Merge sort
    • Quick sort
    • Counting sort
    • Radix sort
    Passage contains an image

    Technical requirements

    To follow along with this chapter, as well as the source code, you are going to require the following:
    • A desktop PC or Notebook with Windows, Linux, or macOS
    • GNU GCC v5.4.0 or above
    • Code Block IDE v17.12 (for Windows and Linux OS) or Code Block IDE v13.12 (for macOS)
    • You will find the code files on GitHub at https://github.com/PacktPublishing/CPP-Data-Structures-and-Algorithms
    Passage contains an image

    Bubble Sort

    Bubble Sort is a simple sorting algorithm, but it has a slow process time. It will divide an input list into two parts— a sublist of items already sorted on the right side and a sublist of items remaining to be sorted in the rest of the list.  If we are going to sort a list of elements in ascending order, the algorithm will move the greatest value to the right position followed by the second greatest value and so on, similar to air bubbles when they rise to the top. Suppose we have an array of unsorted elements and are going to sort them using the Bubble Sort algorithm. The following are the steps required to perform the sorting process:
    1. Compare each pair of adjacent items, for instance array[0] with array[1], array[1] with array[2], and so on.
    2. Swap that pair if the items are not in the correct order. Since we are going to sort in ascending order, the correct order will be array[0] <= array[1], array[1] <= array[2], and so on.
    3. Repeat the first and second steps until the end of the array is reached.
    4. By now, the largest item is in the last position. We can omit this item and repeat step 1 until step 3
  • Data structures based on non-linear relations and data processing methods
    • Xingni Zhou, Zhiyuan Ren, Yanzhuo Ma, Kai Fan, Xiang Ji(Authors)
    • 2020(Publication Date)
    • De Gruyter
      (Publisher)
    Shell sort divides the data into different groups. It first sorts each group and then performs one insertion sort on all the elements, in order to reduce the swapping and moving of data. Shell sort is very efficient, but the quality of grouping will hugely impact the algorithm performance. Shell sort is faster than Bubble Sort and insertion sort, but it is slower than quick sort, merge sort and heap sort. Shell sort is suitable for situations where the number of data is lower than 5,000 and speed is not very important. It is very good for sorting arrays with relatively small amount of data.

    3.7.5  Insertion sort

    Insertion sort keeps inserting the values in the sequence into an already sorted sequence, until the end of this sequence. Insertion sort is an improvement on Bubble Sort. Now it is not widely used. However, since the algorithm is relatively simple, it is still effective for the sorting of some relatively small sequences.

    3.7.6 Bubble Sort

    Bubble Sort is the slowest sorting algorithm. Since it needs to compare each record in the sequence again and again, the number of comparisons is huge. It is the most ineffective algorithm, with a complexity of O(n2 ).

    3.7.7  Selection sort

    This sorting method is a sorting algorithm with swapping, with a complexity of O(n2 ). In actual application it is basically at the same place as Bubble Sort. They are just the initial stages in the development of sorting algorithm and are rarely used in actual applications.

    3.7.8  Bucket sort

    Bucket sort is a sorting strategy that trades space for time. Theoretically, if we use the same number of buckets as the number of records in the sequence, we can achieve linear time complexity. However, when the number of records is huge, it might cause huge space usage, and might even make the sorting impossible. Normally speaking, bucket sort is in practice slower than high-efficiency sorting algorithms such as quick sort. However, it is faster than traditional sorting methods.

    3.7.9  Radix sort

    Radix sort does not follow the same route as the normal sorting algorithms. It is a relatively new algorithm. Radix sort is best used against integers. If we are to apply it to the sorting of floating point numbers, we must be able to map the floating point number into comparisons of multiple keywords, which is really inconvenient.
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.