八大排序之冒泡算法

代码:


import java.util.Scanner;

public class Bubble {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);

		while (in.hasNextInt()) {
			int n = in.nextInt();
			int arr[] = new int[n];
			for (int i = 0; i < arr.length; i++) {
				arr[i] = in.nextInt();
			}

			bubbleSort1(arr, n);
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			bubbleSort2(arr, n);
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
		}

	}

	private static void bubbleSort2(int[] arr, int n) {
		// TODO Auto-generated method stub
		int flag = 0;
		for (int i = 0; i < n-1; i++) {
			for (int j = 0; j < n-1-i; j++) {
				if (arr[j] > arr[j + 1]) {
					int t = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = t;
				}
				flag = 1;
			}
			if (flag == 0) {
				break;
			}
		}
	}

	private static void bubbleSort1(int[] arr, int n) {
		// TODO Auto-generated method stub
		int flag = 0;
		for (int i = n - 1; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (arr[j] > arr[j + 1]) {
					int t = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = t;
				}
				flag = 1;
			}
			if (flag == 0) {
				break;
			}
		}
	}

}

测试结果:

八大排序之冒泡算法_第1张图片

你可能感兴趣的:(八大排序之冒泡算法)