冒泡排序Java实现

冒泡排序

每一趟通过不断交换相邻元素,保证最大元素放在未排序部分的末尾。

时间复杂度 O(n^2).

public class BubbleSort {

	public static void bubbleSort(int[] arr) {
		
		for (int i = arr.length - 1; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (arr[j]>arr[j+1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
	}

	public static void main(String[] args) {

		int[] c = { 4, 9, 23, 1, 45, 27, 5, 2 };
		bubbleSort(c);
		for (int i = 0; i < c.length; i++) {
			System.out.println(c[i]);
		}
	}
}


你可能感兴趣的:(java,冒泡排序)