Home > Java > javaTutorial > body text

Java sorting algorithm: Bubble sorting algorithm implementation (code)

不言
Release: 2018-08-21 14:10:30
Original
1850 people have browsed it

The content this article brings to you is about the Java sorting algorithm: the algorithm implementation (code) of bubble sorting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Bubble sorting method is one of the most basic sorting methods. The operating mechanism of bubble sorting method is a simple sorting achieved by looping through elements and adjusting the order of adjacent elements. method. The essence of bubble sort is to compare two adjacent elements and then swap their positions in ascending or descending order.

The following is the code for descending bubble sorting:

public class Training {
	
	public static void main(String[] args) {
        int [] array = {3,2,5,1,4};
		for (int time = 1; loopTime < array.length; loopTime++) {
			for (int i = 0,temp = 0; i < array.length-loopTime; i++) {
				if (array[i+1]>array[i]) {
					temp = array[i+1];
					array[i+1] = array[i];
					array[i] = temp;
				}
			}
		}
		for (int i = 0; i < array.length; i++) {
			System.out.println(array[i]);
		}
    }
}
Copy after login

Thefor loops each time Looping once will place larger data in the appropriate position, such as loopTime=1; then the largest data will be placed at the end;loopTime=2; then place the second largest data at the penultimate element position; array.length-loopTime :From the perspective of improving the performance of the code, reduce the number of "excess " cycles in this loop;

The following is the running result:

##Of course, there is also bubble sorting in ascending order. In fact, just change "if (array[i 1]>array[i] )" can be changed to array[i 1]
for (int i = 0; i < array.length-time; i++) {
	if (array[i+1]<array[i]) {
		temp = array[i+1];
		array[i+1] = array[i];
		array[i] = temp;
	}
}
Copy after login
Related recommendations:

Java implementation of sorting algorithms: insertion sort, selection sort, bubble sort

##Ten kinds JAVA sorting algorithm example

The above is the detailed content of Java sorting algorithm: Bubble sorting algorithm implementation (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!