Java排序一:冒泡排序

public class TestDemo {
	public static void main(String[] args) {
		int[] arr = new int[10];
		Random random = new Random();
		for (int i = 0; i < arr.length; i++) {
			arr[i] = random.nextInt(100);
		}
		display(arr);
		sort(arr);
		display(arr);
	}

	private static void sort(int[] arr) {
		int len = arr.length;
		for (int i = 0; i < len - 1; i++) {
			for (int j = 0; j < len - i - 1; j++) {
				if (arr[j + 1] < arr[j]) {
					swap(arr, j + 1, j);
				}
			}
		}
	}

	private static void swap(int[] arr, int i, int j) {
		if (i == j) {
			return;
		}
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}

	private static void display(int[] arr) {
		for (int i = 0, len = arr.length; i < len; i++) {
			System.out.print(arr[i] + "  ");
		}
		System.out.println();
	}
}


你可能感兴趣的:(Java排序一:冒泡排序)