冒泡法
public class Test { public static void main(String[] args) { int[] arr = { 9, 5, 6, 3, 8, 2, 1, 4, 7 }; int temp; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] arr = { 9, 5, 6, 3, 8, 2, 1, 4, 7 }; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { arr[j] = arr[j] ^ arr[j + 1]; arr[j + 1] = arr[j] ^ arr[j + 1]; arr[j] = arr[j] ^ arr[j + 1]; } } } System.err.println(Arrays.toString(arr)); } }