Explanation of Array Bubble Sorting Code Example of Java Algorithm

  • 2021-09-04 23:59:53
  • OfStack

Bubble sort is the simplest array lookup algorithm

Bubble sorting principle:
Assuming that the length of an array is k (highest index k-1), traverse the previous k-1 (highest index k-2) elements, if the elements a [i] in the array are compared with the next adjacent element a [i+1], if a [i] > a [i+1], the two elements swap positions. By analogy, if a [i+1] > a [i+2], exchange positions … until the comparison between a [k-2] and a [k-1] is completed, and the 0th iteration ends. At this point, a [k-1] is the maximum value in the array element.

In the first iteration, repeat the above operation for the first k-1 elements of the array a.

In the k-2 iteration, the above operation is repeated for the first two elements of the array a.

Example: {6, 8, 4, 2, 7, 0, 9, 3, 1, 5}

Round 0: 6, 4, 2, 7, 0, 8, 3, 1, 5, 9
Round 1: 4, 2, 6, 0, 7, 3, 1, 5, 8, 9
Round 2: 2, 4, 0, 6, 3, 1, 5, 7, 8, 9
Round 3: 2, 0, 4, 3, 1, 5, 6, 7, 8, 9
Round 4: 0, 2, 3, 1, 4, 5, 6, 7, 8, 9
Round 5: 0, 2, 1, 3, 4, 5, 6, 7, 8, 9
Round 6: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Round 7: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Round 8: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9


public class BubblesTest {
	public static void main(String[] args) {
		int[] array = new int[] {6,8,4,2,7,0,9,3,1,5};
		
		for(int i = 0;i < array.length - 1;i++) {
			for(int j = 0;j < array.length - 1 - i;j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
		for(int i = 0;i < array.length;i++) {
			System.out.println(array[i]);
		}
	}
}

Related articles: