Home > Java > JavaBase > body text

How to implement bubble sorting of arrays in java

王林
Release: 2019-11-26 15:22:18
forward
1936 people have browsed it

How to implement bubble sorting of arrays in java

Bubble sort

Compare two adjacent elements in turn. If the former is greater than the latter, the positions are swapped. After each sorting pass, the The maximum value in this pass is placed last, and the appeal process is repeated until there are no more elements to compare.

java related free learning videos: java learning videos

Examples are as follows:

public class Bubble_Sort {
	public static void main(String[] args){
		int[] arr = {2,4,1,5,6,9,0,6,7};
		bubbleSort(arr);
	}
	// 打印数组
	public static void print(int[] arr){
		for(int i = 0;i < arr.length;i++){
			System.out.print(arr[i]+"\t");
		}
		System.out.println();
	}
	/**
		冒泡排序
		依次比较两个相邻的元素,如果前者大于后者就交换位置
		每一趟排序之后就会把这趟中的最大值放在最后一位
		重复上诉过程,直到没有在需要比较的元素为止
	*/
	public static void bubbleSort(int[] arr){
		
		// 多趟比较,直到没有需要再比较的元素为止,最后的一个值不需要比较
		for(int i = 0;i < arr.length-1;i++){

			// 依次比较相邻的两个元素,每次比较的总个数少一个
			for(int j = 0;j < arr.length-i-1;j++){
				if(arr[j] > arr[j+1]){
					int temp = arr[j+1];
					arr[j+1] = arr[j];
					arr[j] = temp;
				}
			}
			print(arr);
		}
	}
}
Copy after login

Recommended related articles and tutorials: Getting started with java study

The above is the detailed content of How to implement bubble sorting of arrays in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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