java冒泡排序和选择排序

2017-04-27     浏览次数:

//创建一个数组,这个数组的元素是乱序的,然后编程解决将这个数组从小到大打印出来。
public class Work6 {

 

    public static void main(String[] args) {

        int[]arr={5,10,6,4,2,0,8,9,3,15,21,8,16,18};

        //冒泡排序

        /*for (int i = 0; i < arr.length-1; i++) {

            for (int j = 0; j < arr.length-i-1; j++) {

                if (arr[j]>arr[j+1]) {

                    int a=arr[j];

                    arr[j]=arr[j+1];

                    arr[j+1]=a;

                }

            }

        }*/

        //选择排序

        for (int i = 0; i < arr.length-1; i++) {

            for (int j =i+1; j < arr.length; j++) {

                if (arr[i]>arr[j]) {

                    int a=arr[i];

                    arr[i]=arr[j];

                    arr[j]=a;

                }

            }

        }

        //打印结果

        for (int i = 0; i < arr.length; i++) {

            System.out.print(arr[i]+" ");

        }

    }

 

}
*转载请注明出处,更多资料尽在 吾爱编程
返回吾爱编程首页