zoukankan      html  css  js  c++  java
  • cuda中的二分查找

      使用背景

    通常,在做高性能计算时,我们需要随机的连接某些点。这些点都具有自己的度量值,显然,度量值越大的值随机到的概率就会越大。因此,采用加权值得方法:

    void getdegreeSum(DG *g){
        memset(degreeSum,0,sizeof(uint)*MAXSIZE);
        uint i,last=0;
        for(i=0;i<(g->n);i++){
            degreeSum[i] = g->v[i].desum+last;
            last = degreeSum[i];
        }
    }

    这样degreeSum[]数组中存储的即是一个有序的数组,随机生成rand(max),随机数所在的区域的下表就代表选取到的点。

      传统的二分查找函数

    传统的二分查找中,是指定元素,然后查找是否在其中,典型的算法如下:

    int bsearchWithoutRecursion(int array[], int low, int high, int target)
    {
        while(low <= high)
        {
            int mid = (low + high)/2;
            if (array[mid] > target)
                high = mid - 1;
            else if (array[mid] < target)
                low = mid + 1;
            else //find the target
                return mid;
        }
        //the array does not contain the target
        return -1;
    }

    其中Low与high可以根据自己的需求,来定义

      cuda中的二分查找应用

    问题背景:

    指定的一个有序数组,给定一个随机数,要查询随机数所在的区域,即大于前一个值,小于当前值,而当前值的下标,即使所需:

    实现方式:

    __inline__ __device__ int binarySearch(uint *arr,uint length,uint target){
        int left=0;
        int right = length-1;
        while(left < right){
            int middle = (left+right)/2;
            if((target >= arr[middle-1]) && (target < arr[middle])){    //while(rand > degreedis[j])
                return middle;
            }
            else{
                if(target > arr[middle])
                    left = middle+1;
                else
                    right = middle-1;
            }
        }
        return left;
    }

    引用的时候,直接在__global__函数中使用即可,返回值即使要查询的下标。

  • 相关阅读:
    jQuery入门和DOM对象
    jQuery事件
    基础,层次,选择器
    MarkDown快速入门(typora)
    source是读入环境配置文件的命令,不能读入vimrc
    vi中将tab键转化为空格
    django-rest-framework学习之Quickstart和Serializer--2017年4月10日至12日
    Flask-RESTful插件介绍--2017年4月7日
    python restful api 编程--2017年4月6日
    一个验证登录的程序:python编写flask架构restful风格--2017年4月6日
  • 原文地址:https://www.cnblogs.com/xing901022/p/3408540.html
Copyright © 2011-2022 走看看