美文网首页
选择排序和冒泡排序

选择排序和冒泡排序

作者: veneno94 | 来源:发表于2019-06-03 16:06 被阅读0次

    冒泡排序

    public static void bubbleSort() {
            int[] arr = {12,78,34};
            for(int i =0;i<arr.length-1;i++) {
                for(int j=0;j<arr.length-i-1;j++) {//-1为了防止溢出
                    if(arr[j]>arr[j+1]) {
                        int temp = arr[j];
                        arr[j]=arr[j+1];
                        arr[j+1]=temp;
                    }
                }
            }
    
        }
    
    

    选择排序

        public static void selectSort(int[] a) {
            if((a == null) || (a.length == 0))
                return ;
            for(int i = 0;i < a.length - 1;i ++){
                int minIndex = i; // 无序区的最小数据数组下标
                for(int j = i + 1;j < a.length;j ++){
                    // 在无序区中找到最小数据并保存其数组下标
                    if(a[j] < a[minIndex]){
                        minIndex = j;
                    }
                }
                // 将最小元素放到本次循环的前端
                int temp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = temp;
            }
        }
    
    

    相关文章

      网友评论

          本文标题:选择排序和冒泡排序

          本文链接:https://www.haomeiwen.com/subject/ihgcxctx.html