冒泡排序和插入排序

冒泡排序 从第一个开始 遇到比他大的就交换 这样一轮下来最大的就在最后面

public class demo_sort {
    public static void main(String[] args) {
        //冒泡排序算法
        int[] numbers=new int[]{1,5,8,2,3,9,4};
        //需进行length-1次冒泡
        for(int i=0;i<numbers.length-1;i++)
        {
            for(int j=0;j<numbers.length-1-i;j++)
            {
                if(numbers[j]>numbers[j+1])
                {
                    int temp=numbers[j];
                    numbers[j]=numbers[j+1];
                    numbers[j+1]=temp;
                }
            }
        }
        System.out.println("从小到大排序后的结果是:");
        for(i=0;i<numbers.length;i++)
            System.out.print(numbers[i]+" ");
    }
}



//优化



public class bubbleSort {
private int [] array;
public bubbleSort(int [] array) {
this.array=array;
}

public static void main(String[] args) {
int [] a= {3,5,2,8,0,4,7,29,11};
bubbleSort bsort=new bubbleSort(a);
System.out.print("未排序时的数组: ");
bsort.display();
bsort.sort();

}


//打印每次排序后的数组元素
public void display() {
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+"\t");
}
System.out.println();
}


//冒泡排序
public void sort() {
int temp;
int len=array.length;
for(int i=0;i<len-1;i++) { //每次循环,确定一个相对大的数
boolean flag=false; //交换标志位
for(int j=1;j<len-i;j++) { //记录是第几次交换
if(array[j-1]>array[j]) { //如果前者大于后者,开始交换
flag=true; //发生交换
temp=array[j-1];
array[j-1]=array[j];
array[j]=temp;
}
}
System.out.print("第"+(i+1)+"次排序结果:");
display(); //输出交换后的结果
if(!flag) { //如果没有发生交换,证明已经是有序的了,结束排序
break;
}
}
}

}

 

插入排序从第二个元素开 比前面小就往前插 同时其他受影响的元素往后移一位

public class Insert
{
    public static void main(String[] args)
    {
        int[] ins = {2,3,5,1,23,6,78,34};
        int[] ins2 = sort(ins);
        for(int in: ins2){
            System.out.println(in);
        }
    }
 
    public static int[] sort(int[] ins){
        
        for(int i=1; i<ins.length; i++){
            for(int j=i; j>0; j--){
                if(ins[j]<ins[j-1]){
                    int temp = ins[j-1];
                    ins[j-1] = ins[j];
                    ins[j] = temp;
                }
            }
        }
        return ins;
    }
}

 

posted @ 2021-01-09 21:18  数码暴农  阅读(157)  评论(0)    收藏  举报
TOP