[Detailed explanation] Bubble sort <java implementation>

1 Overview

    The core idea of ​​bubble sort:

       Start from the beginning to compare two adjacent elements, and exchange positions when the conditions are met. The conditions can be sorted from small to large, or sorted from large to small. In this way, the maximum value or the minimum value is placed at the last position of the sequence; then the comparisons are performed from the beginning until the entire sequence is in order.  

note:

       ① The comparison process is to compare adjacent elements in the sequence, and the largest or smallest element is placed at the back.

       ② If the better sequence is sorted from small to large, then the largest element after the first comparison is the last of the sequence, and the last element does not need to be compared in the second comparison; therefore, for the second comparison, The number of comparisons is -1, which is -i in the code.

       ③ Loop conditions: Two for loops, the first for loop is the number of comparison passes, and the second for loop is the number of comparisons per pass.

       ④ The arr.length-1 of the second for loop is to prevent the array from going out of bounds. The -i in arr.length-1- i is placed in the back position each time the largest is compared, and the back position is already in order. No need to compare, -i is to subtract the back position

Comparison flow chart:

2. Code implementation:

import java.util.Arrays;

public class Bubble {
	
	public static void main(String[] args) {
		int[] array = {2,5,1,7,3,9,5,10};
		int[] arr1 = bubbling(array);
		System.out.println(Arrays.toString(arr1));
	}
	public static int[] bubbling(int[] arr) {
		
		// 外循环是排序的趟数
		for(int i = 0;i < arr.length - 1;i++) {
			
			// 内循环是每趟比较的次数
			for(int j = 0;j < arr.length - 1 - i;j++) {
				if(arr[j] > arr[j + 1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
		return arr;
	}
}

3. Analysis of algorithm complexity

      Obviously, the time complexity of two for loops is O(n2);

 

 

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/114777303