zoukankan      html  css  js  c++  java
  • 二分查找+冒泡排序(仅示例无说明版)

    二分查找指定数据

    对于一个有序数组,我们通常采用二分查找的方式来定位某一元素,请编写二分查找的算法,在数组中查找指定元素。 
    给定一个整数数组A,同时给定要查找的元素val,请返回它在数组中的位置,若不存在该元素,返回-1。
    若该元素出现多次,请返回第一次出现的位置。

    二分查找的前提是数组必须是有序的,下面是有序数组实现二分查找:

    public class Test {

        public static void main(String[] args) {

            int n[] = {1,2,3,4,5,6,7,8,9};
            System.out.println(getPoint(n,3));;
        }

        public static int getKey(int n[],int val){
            int start = 0;
            int end = n.length-1;
            int result = -1;
            while (start <= end){
                int mid = start + (end - start) / 2;
                if(n[mid] > val){
                    end = mid - 1;
                }else if(n[mid] < val){
                    start = mid + 1;
                }else{
                    return mid;
                }
            }
            return result;
        }

    }

    冒泡实现有序数组

    实现对数组 n 进行排序,包含从小到大,或者从大到小两种情况。

    public class A2 {

        public static void main(String[] args) {
            int n[] = {0,9,3,6,2,1,7,5,8,4};
            System.out.println("正序:"+Arrays.toString(getAscSort(n)));
            System.out.println("倒序:"+Arrays.toString(getDescSort(n)));
        }

        /**
         * 正序
         * @param n
         * @return
         */
        public static int[] getAscSort(int n[]){
            if(n==null||n.length<=1){
                return n;
            }else{
                for (int i = 0; i < n.length - 1; i++) {
                    for (int j = 0; j < n.length - i - 1; j++) {
                        if(n[j]>n[j+1]){
                            int temp = n[j];
                            n[j] = n[j+1];
                            n[j+1] = temp;
                        }
                    }
                }
                return n;
            }
        }

        /**
         * 倒序
         * @param n
         * @return
         */
        public static int[] getDescSort(int n[]){
            if(n==null||n.length<=1){
                return n;
            }else{
                for (int i = 0; i < n.length - 1; i++) {
                    for (int j = 0; j < n.length - i - 1; j++) {
                        if(n[j]<n[j+1]){
                            int temp = n[j];
                            n[j] = n[j+1];
                            n[j+1] = temp;
                        }
                    }
                }
                return n;
            }
        }

    }
  • 相关阅读:
    经常让程序员恼火的一些事情你是否也遇到过一些?
    CRC文件解压缩问题
    你在淘宝买件东西背后的复杂技术 技术普及帖
    程序员需要戒骄戒躁
    IT路上的应该注意自我规划 学习规划与自我修炼
    腾讯,我最恨别人用枪顶着我的头(转)
    软件管理,软件生命周期,软件过程名词解释
    程序员需要掌握的最终技术是什么? “终极技术”:应对困境的方法和信念
    程序员如何缓解“电脑病”
    新浪微博XSS攻击事件
  • 原文地址:https://www.cnblogs.com/niceyoo/p/13684673.html
Copyright © 2011-2022 走看看