冒泡排序
:
图解:
代码实现:
public static void main(String[] args) { int[] a = {1, 0, 34, 23, 67}; int len1 = a.length; for (int i = 0; i < len1 - 1; i++) { for (int j = 0; j < len1 - 1 - i; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } System.out.println(Arrays.toString(a)); }
交换排序
:
思路:
第一个数依次和后面的所有数进行比较,挑出最小的放到最前面,到第二轮从第二个数开始,以此类推
代码实现:
public static void main(String[] args) { int[] b = new int[]{23, 4, 45, 65, 23}; int len2 = b.length; for (int i = 0; i < len2 - 1; i++) { for (int j = i + 1; j < len2; j++) { if (b[i] > b[j]) { int temp = b[i]; b[i] = b[j]; b[j] = temp; } } } System.out.println(Arrays.toString(b)); }