One, foreword

I believe that most of you have learned the course of data structure and algorithm, and we may find a phenomenon is that the books on data structure and algorithm we have learned are basically written in C language, it seems that we have never seen data structure and algorithm written in Java.

With this curiosity, I went to check the data, the domestic basic can’t find the books written using Java data structure and algorithm, there is a book called “Java data structures and algorithms, the code is to use a Java implementation of this book, but this book is the domestic scholars written translation of foreign books, personal feel this book for beginners, It’s a little bit harder to understand.

Bubble sort a running efficiency is very low sorting algorithm, however, although the sorting efficiency is low, it is really a very heavy sorting algorithm, because the idea of bubble sort is the simplest and easiest to understand the sorting algorithm.

Two, bubble sort

1. Definition: Bubble sort is a kind of swap sort by comparing adjacent records in pairs and swapping if they are in reverse order until there are no records in reverse order.

2, the realization of the idea: by comparing the keywords of two adjacent records, the keyword of the first record and the keyword of the second record are compared, if the latter is smaller than the former, the exchange, and then compare the second and third, and so on. After a loop, the largest one has been put in the last position, so that we can recirculate the first N minus 1 number.

Take a group of students of different heights as shown in the picture below:

  • Unranked students

  • Sorted students

  • Bubble sort first round implementation process

Three, bubble sort Java code implementation

1. Bubble sort implementation algorithm:

BubbleSort.java

package BubbleSort;

/** ** Bubble sort implementation algorithm ** /
public class BubbleSort {

    public void bubble(Integer[] data){

        for(int i=0; i<data.length; i++){for(int j=0; j<data.length-1-i; j++){// If the latter is less than the former, the two numbers switch places
                if(data[j]>data[j+1]) {int tmp=data[j];
                    data[j]=data[j+1];
                    data[j+1]=tmp;
                }
            }
        }
    }
}

Copy the code

2, bubble sort test:

Test.java

package BubbleSort;

import java.util.Arrays;

/** ** tests bubble sort ** /
public class Test {

    public static void main(String[] args) {

        Integer[] list={149.138.165.197.176.113.127.114.110};

        // Bubble sort
        BubbleSort bs = new BubbleSort();
        bs.bubble(list);

        System.out.println("The result before sorting is:" + Arrays.toString(list));
        System.out.print("The sorted result is:");

        for(int i=0; i<list.length; i++){ System.out.print(list[i]+""); }}}Copy the code

2. Test Results:

Scan the QR code to follow the wechat official account to learn more