排序

public class Pro2java {

        public static void binarySort(int[] source) {
            int i, j;
            int high, low, mid;
            int temp;
            for (i = 1; i < source.length; i++) {
                // 查找区上界
                low = 0;
                // 查找区下界
                high = i - 1;
                //将当前待插入记录保存在临时变量中
                temp = source[i];
                while (low <= high) {
                    // 找出中间值
                     mid = (low + high) / 2;
                   // mid = (low + high) >> 1;
                    //如果待插入记录比中间记录小
                    if (temp<source[mid] ) {
                        // 插入点在低半区
                        high = mid - 1;
                    } else {
                        // 插入点在高半区
                        low = mid + 1;
                    }
                }
                //将前面所有大于当前待插入记录的记录后移
                for (j = i - 1; j >=low; j--) {
                    source[j + 1] = source[j];
                }
                //将待插入记录回填到正确位置.
                source[low] = temp;
                System.out.print("第" + i + "趟排序:");
                printArray(source);
            }
        }

        private static void printArray(int[] source) {
            for (int i = 0; i < source.length; i++) {
                System.out.print("\t" + source[i]);
            }
            System.out.println();
        }

        public static void main(String[] args) {
            int source[] = new int[] { 12, 15, 9, 14, 4, 18, 23, 6 };
            System.out.print("初始关键字:");
            printArray(source);
            System.out.println("");

            binarySort(source);

            System.out.print("\n\n排序后结果:");
            printArray(source);
        }
    }


冒泡:

public class Pro1java {
    public static void arrprint(int[] s){
        for (int i = 0; i < s.length; i++) {
            System.out.print(s[i]+"\t");
        }
    }
    public static void maop(int[] s){
        int temp;//定义一个临时变量
        for (int i = 0; i <s.length-1 ; i++) {
            for (int j = 0; j < s.length-1-i; j++) {
                if(s[j+1]<s[j]){
                    temp=s[j];
                    s[j]=s[j+1];
                    s[j+1]=temp;

                }

            }

        }

    }
    public static void main(String[] args) {
        int s[]=new int[]{1,3,8,2,6,5,10,4,9};
        System.out.println("初始值为:");
        arrprint(s);
        maop(s);
        System.out.println("结果为:");
        arrprint(s);

    }

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值