Home php教程 PHP开发 Three implementations of bubble sort

Three implementations of bubble sort

Dec 19, 2016 pm 01:15 PM
Bubble Sort

Bubble sorting is very easy to understand and implement, take sorting from small to large as an example:

Suppose the array length is N.

1. Compare the two adjacent data before and after. If the former data is greater than the latter data, the two data will be exchanged.

2. In this way, after traversing the 0th data to the N-1th data of the array, the largest data will "sink" to the N-1th position of the array.

3. N=N-1, if N is not 0, repeat the previous two steps, otherwise the sorting is completed.

It is easy to write the code by definition:

//冒泡排序1  
void BubbleSort1(int a[], int n)  
{  
       int i, j;  
       for (i = 0; i < n; i++)  
              for (j = 1; j < n - i; j++)  
                     if (a[j - 1] > a[j])  
                            Swap(a[j - 1], a[j]);  
}
Copy after login

Let’s optimize it and set a flag, which is true if an exchange occurs on this trip, otherwise it is false. Obviously, if there is no exchange in one trip, it means that the sorting has been completed.

//冒泡排序2  
void BubbleSort2(int a[], int n)  
{  
       int j, k;  
       bool flag;  
  
       k = n;  
       flag = true;  
       while (flag)  
       {  
              flag = false;  
              for (j = 1; j < k; j++)  
                     if (a[j - 1] > a[j])  
                     {  
                            Swap(a[j - 1], a[j]);  
                            flag = true;  
                     }  
              k--;  
       }  
}
Copy after login

Let’s do further optimization. If there is an array of 100 numbers, only the first 10 are unordered, and the next 90 are all sorted and all are greater than the first 10 numbers, then after the first traversal, the last position where the exchange occurs must be less than 10, and this The data after the position must be in order. Record this position. The second time you just need to traverse from the head of the array to this position.

//冒泡排序3  
void BubbleSort3(int a[], int n)  
{  
    int j, k;  
    int flag;  
      
    flag = n;  
    while (flag > 0)  
    {  
        k = flag;  
        flag = 0;  
        for (j = 1; j < k; j++)  
            if (a[j - 1] > a[j])  
            {  
                Swap(a[j - 1], a[j]);  
                flag = j;  
            }  
    }  
}
Copy after login

Bubble sorting is, after all, an inefficient sorting method and can be used when the data size is small. When the data size is relatively large, it is best to use other sorting methods.


For more articles related to the three implementations of bubble sorting, please pay attention to the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

Transform code with C++ function pointers: improve efficiency and reusability Transform code with C++ function pointers: improve efficiency and reusability Apr 29, 2024 pm 06:45 PM

Function pointer technology can improve code efficiency and reusability, specifically as follows: Improved efficiency: Using function pointers can reduce repeated code and optimize the calling process. Improve reusability: Function pointers allow the use of general functions to process different data, improving program reusability.

How to implement bubble sort algorithm in C# How to implement bubble sort algorithm in C# Sep 19, 2023 am 11:10 AM

How to implement the bubble sort algorithm in C# Bubble sort is a simple but effective sorting algorithm that arranges an array by comparing adjacent elements multiple times and exchanging positions. In this article, we will introduce how to implement the bubble sort algorithm using C# language and provide specific code examples. First, let us understand the basic principles of bubble sort. The algorithm starts from the first element of the array and compares it with the next element. If the current element is larger than the next element, swap their positions; if the current element is smaller than the next element, keep it

Guide to writing a custom sorting algorithm for PHP arrays Guide to writing a custom sorting algorithm for PHP arrays Apr 27, 2024 pm 06:12 PM

How to write a custom PHP array sorting algorithm? Bubble sort: Sorts an array by comparing and exchanging adjacent elements. Selection sort: Select the smallest or largest element each time and swap it with the current position. Insertion sort: Insert elements one by one into the sorted part.

Complexity analysis of various PHP array sorting algorithms Complexity analysis of various PHP array sorting algorithms Apr 27, 2024 am 09:03 AM

PHP array sorting algorithm complexity: Bubble sort: O(n^2) Quick sort: O(nlogn) (average) Merge sort: O(nlogn)

Analyze time complexity and space complexity in Go language Analyze time complexity and space complexity in Go language Mar 27, 2024 am 09:24 AM

Go is an increasingly popular programming language that is designed to be easy to write, easy to read, and easy to maintain, while also supporting advanced programming concepts. Time complexity and space complexity are important concepts in algorithm and data structure analysis. They measure the execution efficiency and memory size of a program. In this article, we will focus on analyzing the time complexity and space complexity in the Go language. Time Complexity Time complexity refers to the relationship between the execution time of an algorithm and the size of the problem. Time is usually expressed in Big O notation

Algorithm selection and optimization techniques in C++ function performance optimization Algorithm selection and optimization techniques in C++ function performance optimization Apr 23, 2024 pm 06:18 PM

C++ function performance optimization algorithm selection: Choose efficient algorithms (such as quick sort, binary search). Optimization skills: inline small functions, optimize caching, avoid deep copies, and loop unrolling. Practical case: When searching for the maximum element position of an array, binary search and loop expansion are used after optimization, which greatly improves performance.

Java Data Structures and Algorithms: A Practical Guide to Cloud Computing Java Data Structures and Algorithms: A Practical Guide to Cloud Computing May 09, 2024 am 08:12 AM

The use of data structures and algorithms is crucial in cloud computing for managing and processing massive amounts of data. Common data structures include arrays, lists, hash tables, trees, and graphs. Commonly used algorithms include sorting algorithms, search algorithms and graph algorithms. Leveraging the power of Java, developers can use Java collections, thread-safe data structures, and Apache Commons Collections to implement these data structures and algorithms.

See all articles