排序算法之冒泡
阿新 • • 發佈:2018-07-05
pub i++ 打印 win lse wss noi rand 進行
- 1.原理
- 2.java源碼
- 3.打印結果
import java.util.Random; /** * * <p> * Description:冒泡排序 * <p> * * @author gaozhen * @date 2018年6月30日 * @Version 1.0 */ public class BubleSort { public static void main(String[] agrs) { final int MAX_SIZE = 10; int[] array = new int[MAX_SIZE]; Random random = new Random(); for (int i = 0; i < MAX_SIZE; i++) { array[i] = random.nextInt(MAX_SIZE); } System.out.println("排序前:"); print(array); System.out.println("開始排序..."); array = sort(array); System.out.println("排序完成"); System.out.println("排序後:"); print(array); } public static int[] sort(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { /** * 每做完一次循環,第nums.length-i大移到合適的位置 */ for (int j = 0; j < nums.length - 1 - i; j++) { if (nums[j] > nums[j + 1]) { int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } print(nums); } return nums; } public static void print(int[] nums) { for (int i : nums) { System.out.print(i + "\t"); } System.out.println(); } }
3.打印結果 排序前: 8 8 5 2 3 5 6 1 2 9 開始排序... 8 5 2 3 5 6 1 2 8 9 //找到最大的9 5 2 3 5 6 1 2 8 8 9 //找到第二大的8 2 3 5 5 1 2 6 8 8 9 //找到第三大的8 2 3 5 1 2 5 6 8 8 9 //以此類推 2 3 1 2 5 5 6 8 8 9 2 1 2 3 5 5 6 8 8 9 1 2 2 3 5 5 6 8 8 9 1 2 2 3 5 5 6 8 8 9 1 2 2 3 5 5 6 8 8 9 排序完成 排序後: 1 2 2 3 5 5 6 8 8 9
排序算法之冒泡