Bubble sort - Bubble Sort

Bubble Sort regarded as a simple and intuitive sorting algorithm.
The time complexity is O (n * n)
space complexity is O (1)

Basic procedure 1. Algorithm

Comparison of two adjacent elements, if the first is greater than the second, two exchanged order.
After ordering again last element will be the largest number.
Then repeat the above steps (except the last one through the largest element) for the remaining elements, until finally there is no need to compare a pair of numbers.

2. moving map presentation

FIG movable from -https: //www.runoob.com/w3cnote/bubble-sort.htmlNote: The above is taken from FIG movable novice tutorial

3. JAVA code implementation

package com.devin.algorithms;

public class BubbleSortDemo {
	public static void main(String[] args) {
		int[] data = new int[] { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };

		System.out.println(">>>>>>>>before doing bubble sort>>>>>>>>>");
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i] + ",");
		}
		System.out.println();

		// Do Bubble Sort
		for (int i = 1; i < data.length; i++) {
			for (int j = 0; j < data.length - i; j++) {
				if (data[j] > data[j + 1]) {
					int temp = data[j];
					data[j] = data[j + 1];
					data[j + 1] = temp;
				}
			}
		}

		System.out.println(">>>>>>>>after doing bubble sort>>>>>>>>>");
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i] + ",");
		}
	}
}

Results are as follows:

>>>>>>>>before doing bubble sort>>>>>>>>>
3,44,38,5,47,15,36,26,27,2,46,4,19,50,48,
>>>>>>>>after doing bubble sort>>>>>>>>>
2,3,4,5,15,19,26,27,36,38,44,46,47,48,50,
Released seven original articles · won praise 3 · Views 238

Guess you like

Origin blog.csdn.net/devin_xin/article/details/103277778