冒泡排序
假设有一数组int [] arr = {9,5,4,10,2};原理是第一个元素和第二个比较,如果前者大于后者便交换位置,然后第二个元素和第三个元素比较,如果前者大于后者便交换位置。以此类推,最大的那个会依次跑到数组的最后面。
public static void main(String[] args) { int [] arr = {9,5,4,10,2}; for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j+1]) { int tmp; tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } /** * 输出每次循环之后数据的顺序,便于观察、理解 * 输出结果 * 2,5,4,10,9 * 2,4,5,10,9 * 2,4,5,10,9 * 2,4,5,9,10 */ for (int k = 0; k < arr.length; k++) { System.out.print(k == arr.length - 1 ? arr[k] : arr[k] + "," ); } System.out.println(); } }
选择排序
原理:先假设第一个元素就是最小的,定义下标min = 0;第一个元素先和第二个元素比较,如果第一个元素大于第二个元素,就把第二个元素的下标定义为最小的,然后继续和后面的元素比较,以此类推,循环一次,如果有比第一个元素小的,就会和第一个元素交换位置。
public static void main(String[] args) { int [] arr = {9,5,4,10,2}; for (int i = 0; i < arr.length - 1; i++) { int min = i; for (int j = i+1; j < arr.length; j++) { if (arr[min] > arr[j]) { min = j; } } if (min != i) { int tmp; tmp = arr[min]; arr[min] = arr[i]; arr[i] = tmp; } /** * 输出结果 * 2,5,4,10,9 * 2,4,5,10,9 * 2,4,5,10,9 * 2,4,5,9,10 */ for (int k = 0; k < arr.length; k++) { System.out.print(k == arr.length - 1 ? arr[k] : arr[k] + "," ); } System.out.println(); } }