0
点赞
收藏
分享

微信扫一扫

冒泡排序与选择排序(Java)

宁静的猫 2022-01-06 阅读 34

 1.冒泡排序

import java.util.Arrays;

public class BubbleSort{
	public static void main(String[] args){
		int[] bubble = new int[6];

        //数组赋值
		for(int i = 0; i < bubble.length; i++){
			bubble[i] = (int) (Math.random() * 20) + 1;
		}

		int[] bubble1 = Arrays.copyOf(bubble,bubble.length);  //利用Arrays工具类的copyOf、sort()方法判断排序是否成功

		System.out.println("bubble排序前" + Arrays.toString(bubble));   //打印最初数组
		System.out.println("-------------------------------------------");

        //冒泡排序
        优化:bubble-1-j,经过一次或多次排序后,数组末尾已经为有序,不用再进行比较
		for(int j = 0; j < bubble.length- 1; j++){
			boolean flag = true;
			for(int i = 0; i < bubble.length - 1 - j; i++){
				if(bubble[i] > bubble[i + 1]){
					int t = bubble[i];
					bubble[i] = bubble[i + 1];
					bubble[i + 1] = t;
					flag = false;
				}
			}
			System.out.println(Arrays.toString(bubble));
			if(flag == true){
				break;
			}
		}
		System.out.println("-------------------------------------------");
		System.out.println("bubble1排序前" + Arrays.toString(bubble1));
		System.out.println("-------------------------------------------");
		System.out.println("bubble排序后" + Arrays.toString(bubble));
		Arrays.sort(bubble1);
		System.out.println("bubble1排序后" + Arrays.toString(bubble1));
		System.out.println(Arrays.equals(bubble,bubble1));
	}
}

2.选择排序

import java.util.Arrays;

public class SelectionSort{
	public static void main(String[] argjs){
		int[] selection = new int[6];

		for(int i = 0; i < selection.length; i++){
			selection[i] = (int) (Math.random() * 20) + 1;
		}

		int[] selection1 = Arrays.copyOf(selection, selection.length);

		System.out.println("selection排序前" + Arrays.toString(selection));
		System.out.println("selection1排序前" + Arrays.toString(selection1));
		System.out.println("-------------------------------------------");
		
        //选择排序
        //内层循环从固定位置的下一位开始
        for(int j = 0; j < selection.length - 1; j++){
			for(int i = j + 1; i < selection.length; i++){
				if(selection[j] > selection[i]){
					int t = selection[i];
					selection[i] = selection[j];
					selection[j] = t;
				}
			}
			System.out.println(Arrays.toString(selection));
		}
		System.out.println("-------------------------------------------");
		System.out.println("selection排序后" + Arrays.toString(selection));
		Arrays.sort(selection1);
		System.out.println("selection1排序后" + Arrays.toString(selection1));
		System.out.println(Arrays.equals(selection, selection1));
	}
}
举报

相关推荐

0 条评论