Java array sorting - bubble sort

There are many ways to sort arrays in Java, including bubble sort, selection sort, insertion sort, etc. This article will talk about the implementation of bubble sort.

Bubble sort actually compares two adjacent elements of an array, and puts the larger elements backward. When the first comparison is completed, the largest element will be arranged to the far right of the array, so the comparison continues in the same way. , you will get a sorted array.


It is regular:

1 After each comparison, the relatively largest value will be placed on the right side of the array

2 After each comparison, the next comparison reduces the comparison by one element

3 A total of length-1 times of the length of the array needs to be compared

Draw a picture to help understand :

-------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Write an example and run it

public class BubbleDemo {
	public static void main(String[] args) {
		int[] arr = new int[] { 2, 34, 56, 43, 45 };

		int[] arr2 = getBubble(arr);
		for (int a : arr2) {
			System.out.print(a + " ");
		}
	}

	public static int[] getBubble(int[] arr) {
		// Bubble Sort
		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;
	}
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641933&siteId=291194637