Ejemplo n.º 1
0
 int search(vector<int>& nums, int target) {
     int n = nums.size();
     // if (n == 0) return -1;
     // if (n == 1) return (target == nums[0])-1;
     
     //find pivot
     int pivot = -1;
     int l = 0, r = n-1;
     while (l < r)
     {
         int mid = l + (r-l)/2;
         nums[mid] > nums[r]? l = mid+1: r = mid;
     }
     pivot = r-1; //index of maximum
     cout <<pivot;
     if (pivot == -1) //all ascending
         return BinarySearch(nums, 0, n-1, target);
     // if (target > nums[pivot] || target < nums[r] || (target >nums[n-1] && target < nums[0]))
     //     return -1;
     else if (target >=nums[0])
         return BinarySearch(nums, 0, pivot, target);
     else
         return BinarySearch(nums, pivot+1, n-1, target);
 
 }
Ejemplo n.º 2
0
size_t CosineTree::BinarySearch(arma::vec& cDistribution,
                                double value,
                                size_t start,
                                size_t end)
{
  size_t pivot = (start + end) / 2;

  // If pivot is zero, first point is the sampled point.
  if (!pivot)
  {
    return pivot;
  }

  // Binary search recursive algorithm.
  if (value > cDistribution(pivot - 1) && value <= cDistribution(pivot))
  {
    return (pivot - 1);
  }
  else if (value < cDistribution(pivot - 1))
  {
    return BinarySearch(cDistribution, value, start, pivot - 1);
  }
  else
  {
    return BinarySearch(cDistribution, value, pivot + 1, end);
  }
}
int BinarySearch(int A[],int low,int high,int x){
    if (low > high) return -1;
    int mid = low + (high-low)/2; //low+high can overflow
    if(x == A[mid]) return mid;   // Found X, return (exit)
    else if(x < A[mid]) return BinarySearch(A, low, mid-1,x); //X lies before mid
    else return BinarySearch(A, mid+1, high, x);   //X lies after mid
}
Ejemplo n.º 4
0
//CDynamicArray &aWord: the words array
//CDynamicArray &aWordBinaryNet:the net between words
//double dSmoothingPara: the parameter of data smoothing
//CDictionary &DictBinary: the binary dictionary
//CDictionary &DictCore: the Core dictionary
bool CSegment::BiGraphGenerate(CDynamicArray &aWord, CDynamicArray &aBinaryWordNet,double dSmoothingPara,CDictionary &DictBinary,CDictionary &DictCore)
{
	PARRAY_CHAIN pTail,pCur,pNextWords;//Temp buffer
	unsigned int nWordIndex=0,nTwoWordsFreq=0,nCurWordIndex,nNextWordIndex;
	//nWordIndex: the index number of current word
	double dCurFreqency,dValue,dTemp;
	char sTwoWords[WORD_MAXLENGTH];
	m_nWordCount=aWord.GetTail(&pTail);//Get tail element and return the words count
	if(m_npWordPosMapTable)
	{//free buffer
		delete [] m_npWordPosMapTable;
		m_npWordPosMapTable=0;
	}
	if(m_nWordCount>0)//Word count is greater than 0
        {
		m_npWordPosMapTable=new int[m_nWordCount];//Record the  position of possible words
                memset(m_npWordPosMapTable,0,m_nWordCount*sizeof(int));
        }
	pCur=aWord.GetHead();
	while(pCur!=NULL)//Set the position map of words
	{
		m_npWordPosMapTable[nWordIndex++]=pCur->row*MAX_SENTENCE_LEN+pCur->col;
		pCur=pCur->next;
	}

	pCur=aWord.GetHead();
	while(pCur!=NULL)//
	{
		if(pCur->nPOS>=0)//It's not an unknown words
			dCurFreqency=pCur->value;
		else//Unknown words
			dCurFreqency=DictCore.GetFrequency(pCur->sWord,2);
		aWord.GetElement(pCur->col,-1,pCur,&pNextWords);//Get next words which begin with pCur->col
		while(pNextWords&&pNextWords->row==pCur->col)//Next words
		{	
			//Current words frequency
			strcpy(sTwoWords,pCur->sWord);
			strcat(sTwoWords,WORD_SEGMENTER);
			strcat(sTwoWords,pNextWords->sWord);
			nTwoWordsFreq=DictBinary.GetFrequency(sTwoWords,3);
			//Two linked Words frequency
			dTemp=(double)1/MAX_FREQUENCE;
			//Smoothing
			dValue=-log(dSmoothingPara*(1+dCurFreqency)/(MAX_FREQUENCE+80000)+(1-dSmoothingPara)*((1-dTemp)*nTwoWordsFreq/(1+dCurFreqency)+dTemp));
			//-log{a*P(Ci-1)+(1-a)P(Ci|Ci-1)} Note 0<a<1
			if(pCur->nPOS<0)//Unknown words: P(Wi|Ci);while known words:1
			    dValue+=pCur->value;

			//Get the position index of current word in the position map table
			nCurWordIndex=BinarySearch(pCur->row*MAX_SENTENCE_LEN+pCur->col,m_npWordPosMapTable,m_nWordCount);
			nNextWordIndex=BinarySearch(pNextWords->row*MAX_SENTENCE_LEN+pNextWords->col,m_npWordPosMapTable,m_nWordCount);
			aBinaryWordNet.SetElement(nCurWordIndex,nNextWordIndex,dValue,pCur->nPOS);
			pNextWords=pNextWords->next;//Get next word
		}
		pCur=pCur->next;
	}
	return true;
}
int BinarySearch(int arr[],int first,int last,int target){
	int mid;
	if(first>last) return -1;
	mid=(first+last)/2;

	if(arr[mid]==target) return mid;
	else if(arr[mid]>target) return BinarySearch(arr,first,mid-1,target);
	else return BinarySearch(arr,mid+1,last,target);
}
Ejemplo n.º 6
0
int _tmain(int argc, _TCHAR* argv[])
{
	int i = BinarySearch(a, 101, 0, kSize);
	i = BinarySearch(a, 76, 0, kSize);

	i = BinarySearchIterative(a, 77, 0, kSize);
	i = BinarySearchIterative(a, 3, 0, kSize);
	i = BinarySearchIterative(a, 101, 0, kSize);
	i = BinarySearchIterative(a, 76, 0, kSize);
	return 0;
}
Ejemplo n.º 7
0
// 在a的[low, high]区间内找到ley的位置并返回
int BinarySearch(int* a, int low, int high, int key){
	if(low > high) return -1;
	// 算出中间位置
	int mid = (low + high) / 2;

	if(key > a[mid]){
		return BinarySearch(a, mid + 1, high, key);
	} else if(key < a[mid]){
		return BinarySearch(a, low, mid - 1, key);
	} else return mid;
}
Ejemplo n.º 8
0
void Table3D::InterpolatePoint_old(void) {
  // Dimension 1
  BinarySearch(interp->index[0], interp->weight[0][0], x1, 0, n1-1, point[0]);
  interp->weight[0][1] = 1.0 -interp->weight[0][0];
  // Dimension 2
  BinarySearch(interp->index[1], interp->weight[1][0], x2, 0, n2-1, point[1]);
  interp->weight[1][1] = 1.0 -interp->weight[1][0];
  // Dimension 3
  BinarySearch(interp->index[2], interp->weight[2][0], x3, 0, n3-1, point[2]);
  interp->weight[2][1] = 1.0 -interp->weight[2][0];
}
Ejemplo n.º 9
0
// Returns the index of number within array a or -1 if not found
int BinarySearch(const int a[], int number, int low, int high)
{
	if (low < 0 || high < 0) return -1;
	if (low > high) return -1;

	int mid = (low + high) / 2;
	if (number == a[mid]) return mid;
	else if (number < a[mid])
		return BinarySearch(a, number, low, mid - 1);
	else // number > a[mid]
		return BinarySearch(a, number, mid + 1, high);
}
Ejemplo n.º 10
0
int BinarySearch(int* arr, int key, int min_idx, int max_idx) {
    if(max_idx < min_idx) {
        return -1; // Not Found
    }
    int mid_idx = min_idx + ((max_idx - min_idx) / 2);
    if(key < arr[mid_idx]) {
        return BinarySearch(arr, key, min_idx, mid_idx - 1);
    }
    if(key > arr[mid_idx]) {
        return BinarySearch(arr, key, mid_idx + 1, max_idx);
    }
    return mid_idx;
}
Ejemplo n.º 11
0
int main(int argc, char** argv){
   int i, j, k, m;
   int A[] = {2,5,-3,45,12,4,8,19,3,12};
   int B[] = {2,4,6,8,10,12,14,16,18,20};

   i = SequentialSearch(A, 10, 12);
   j = SequentialSearch(B, 10, 12);
   k = BinarySearch(B, 10, 12);
   m = BinarySearch(B, 10, 13);

   printf("%d, %d, %d, %d\n", i, j, k, m);

   return(EXIT_SUCCESS);
}
Ejemplo n.º 12
0
/* Search an ordered array of strings in a recursive binary fashion.
 * Returns the index of the string found. Less than 0 if false.
 */
int BinarySearch(char *name,int l, int h, char *array[])

{
    register int m, rc;

    if (l > h)
        return (-1);
    m = (l + h) / 2;
    if ((rc = strcmp(name, array[m])) == 0)
        return (m);
    else if (rc < 0)
        return (BinarySearch(name, l, m - 1, array));
    else
        return (BinarySearch(name, m + 1, h, array));
}
Ejemplo n.º 13
0
int BinarySearchType::BinarySearch(/* IN    */ int First,
			                       /* IN    */ int Last)
    //-------------------------------------------------
	// Pre : First, Last and Value are assigned
	//       and 0 <= First, Last <= SIZE-1, 
    //           where SIZE is the maximum size of the array,
	//       and pDC_[First..Last] and pValue_ are assigned
	// Post: pDC_ has been search for Value point to by pValue_
	//       if Value is found
	//          returns index within DataContainer
	//       else
	//			returns -1
	//-------------------------------------------------

{
  int Index;

  if (First > Last)
  {
      Index = -1;      // Value not in original DataContainer
  }
  else
  {
      int Mid = (First + Last)/2;

      //if (Value == A[Mid])
	  if ((*pValue_) == pDC_->GetItem(Mid))
	  {
        Index = Mid;       // Value found at DataContainer[Mid]
	  }		
     // else if (Value < A[Mid])
	  else if ((*pValue_) < pDC_->GetItem(Mid))
	  {
        //BinarySearch(A, First, Mid-1, Value, Index);  // X
        Index = BinarySearch(First, Mid-1);  // X
	  }		

      else
	  {
        //BinarySearch(A, Mid+1, Last, Value, Index);   // Y
        Index = BinarySearch(Mid+1, Last);   // Y
	  }

  }  // end else

  return (Index);

}  // end BinarySearch
Ejemplo n.º 14
0
void *multiGenerateSplit(void *arg)
{
	void **argT=(void **)arg;
	uint64_t num=(uint64_t )argT[0];
	uint64_t THREAD_NUM=(uint64_t)argT[1];
	free(argT);
	uint64_t segment=BWTLEN/THREAD_NUM;
	uint64_t start=num*segment,i;
	uint64_t specialSApoint,branchPoint;
	specialSApoint=BinarySearch(start,specialSA,countRead-1);
	branchPoint=BinarySearch(start,specialBranch,specialBranchNum-1);
	for(i=start;i<BWTLEN;i++)
	{
		unsigned int multioutFlag=0;
		//check whether is multiout or not
		uint64_t distance=specialSA[specialSApoint]-i;
		if(distance>=KMER_LENGTH)// use the main module, for kmer info was stored in it
		{
			uint64_t checkSeq=convert(i)>>((32-KMER_LENGTH)<<1);
			unsigned int formerSeq=checkSeq>>(REDLEN<<1);
			uint64_t latterSeq=(checkSeq&REDEXTRACT);
			uint64_t redLen;
			//operation to check multiout, use hash
			if(formerSeq>0)
			{
				redLen=blackTable[formerSeq]-blackTable[formerSeq-1];
			}
			else
			{
				redLen=blackTable[0];
			}
			if(redLen>0)
			{
				//binary search
				uint64_t startPoint=blackTable[formerSeq]-redLen;
				uint64_t *searchRedSeq=&redSeq[startPoint];
				uint64_t candidate=BinarySearch_red(latterSeq,searchRedSeq,redLen-1);
				if(candidate<redLen)
				{
					if((searchRedSeq[candidate]>>2)==latterSeq)
					{
						// Then we can judge whether it is multiout
						unsigned int tempFlag=searchRedSeq[candidate]&3;
						multioutFlag=tempFlag&1;
					}
				}
			}
		}
Ejemplo n.º 15
0
void findSorted(int *list,int k,int n)
{
     int i,j;
     int x,y,IndexX=-1,IndexY=-1;
     int low,high;
     FILE *out=fopen("output.txt","w");
     for(i=0; i<n ; i++)
     {
        
         x= list[i];
         IndexX=i;
         
         y=k-x;
         
         IndexY=BinarySearch(list,y,n);
         
         if(IndexY==-1)
               printf("There is no x+y=k exist\n\n");
         else if(list[IndexX] < list[IndexY])
         {
               printf("List[%d]'s element is %d\nList[%d]'s element is %d\n",IndexX,list[IndexX],IndexY,list[IndexY]);
               printf("Sum of these is equal to %d\n\n",k);
         
               
               fprintf(out,"%d %d \n",list[IndexY], list[IndexX]);
               
         }
     
     }   
     fclose(out);
     
          

}
Ejemplo n.º 16
0
void CosineTree::ColumnSamplesLS(std::vector<size_t>& sampledIndices,
                                 arma::vec& probabilities,
                                 size_t numSamples)
{
  // Initialize the cumulative distribution vector size.
  arma::vec cDistribution;
  cDistribution.zeros(numColumns + 1);

  // Calculate cumulative length-squared distribution for the node.
  for (size_t i = 0; i < numColumns; i++)
  {
    cDistribution(i + 1) = cDistribution(i) +
        (l2NormsSquared(i) / frobNormSquared);
  }

  // Initialize sizes of the 'sampledIndices' and 'probabilities' vectors.
  sampledIndices.resize(numSamples);
  probabilities.zeros(numSamples);

  for (size_t i = 0; i < numSamples; i++)
  {
    // Generate a random value for sampling.
    double randValue = arma::randu();
    size_t start = 0, end = numColumns, searchIndex;

    // Sample from the distribution and store corresponding probability.
    searchIndex = BinarySearch(cDistribution, randValue, start, end);
    sampledIndices[i] = indices[searchIndex];
    probabilities(i) = l2NormsSquared(searchIndex) / frobNormSquared;
  }
}
Ejemplo n.º 17
0
size_t CosineTree::ColumnSampleLS()
{
  // If only one element is present, there can only be one sample.
  if (numColumns < 2)
  {
    return 0;
  }

  // Initialize the cumulative distribution vector size.
  arma::vec cDistribution;
  cDistribution.zeros(numColumns + 1);

  // Calculate cumulative length-squared distribution for the node.
  for (size_t i = 0; i < numColumns; i++)
  {
    cDistribution(i + 1) = cDistribution(i) +
        (l2NormsSquared(i) / frobNormSquared);
  }

  // Generate a random value for sampling.
  double randValue = arma::randu();
  size_t start = 0, end = numColumns;

  // Sample from the distribution.
  return BinarySearch(cDistribution, randValue, start, end);
}
Ejemplo n.º 18
0
	/*!
	  \brief Nearest Neighbor search function
	  Searches for the k nearest neighbors to the point q.  The answer
	  vector returned will contain the indexes to the answer points
	  This function is thread-safe.
	  \param q The query point
	  \param k The number of neighbors to return
	  \param nn_idx Answer vector
	  \param dist Distance Vector
	  \param eps Error tolerence, default of 0.0.
	*/
	void ksearch(Point q, unsigned int k, std::vector<long unsigned int> &nn_idx, std::vector<double> &dist, float Eps) {
		long unsigned int query_point_index;
		qknn que;
		query_point_index = BinarySearch(points, q, lt);
		ksearch_common(q, k, query_point_index, que, Eps);
		que.answer(nn_idx, dist);
	}
Ejemplo n.º 19
0
int main()
{
  int n,i,j,temp,arr[100],lower,upper,search,s;
    printf("\nEnter the number of elements :\n");
  scanf("%d",&n);
  printf("Enter the elements :\n");
  for(i=0;i<n;i++)
  scanf("%d",&arr[i]);
  printf("Enter the element to be searched :\n");
  scanf("%d",&search);
  lower=0;
  upper=n;
  for(i=0;i<n-1;i++)
  {
      for(j=i+1;j<n;j++)
      {
          if(arr[i]>arr[j])
          {
            temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
          }
      }
  }
  s=BinarySearch(lower,upper,arr,search);
  if(s==-1)
    printf("The element %d is not present in the array\n",search);
  else
    printf("The element %d is in position %d\n",search,s);
  
  
  
  return 0;
}
Ejemplo n.º 20
0
int main() {
     
    int myArray[10], val, answer;
    srand(time(0));
    
    // Fill the array randomly, then sort. 
    randArray(myArray, 10, 100);
    
    // Print out the original contents.
    printf("Here are the values in your array: ");
    printArray(myArray, 10);
    
    bubbleSort(myArray, 10);
        
    // Print out the contents after the sort.
    printf("Here are the values in your array: ");
    printArray(myArray, 10);
    
    // Ask the user for an element for which to search.
    printf("For which element would you like to search?");
    scanf("%d", &val);
    
    // Perform a binary search.
    answer = BinarySearch(myArray, 10, val);
    
    // Print out the results!
    if (answer != NOT_FOUND)
       printf("Your value was found in index %d of the array.\n", answer);
    else
       printf("Your value wasn't found.\n");
        
    system("PAUSE");
    return 0;
}
Ejemplo n.º 21
0
int main(int argc,char **argv)
{
	int32_t num,search,i = 0,result = 0;

	fprintf(stdout,"Enter the number of elements :\n");
	fscanf(stdin,"%d",&num);
	int32_t *array = (int32_t *)malloc(sizeof(int32_t) * num);
	fprintf(stdout,"Enter the elements :\n");
	while(i < num)
	{
		fscanf(stdin,"%d",(array + i));
		i++;
	}
	fprintf(stdout,"Enter the element to be searched :\n");
	fscanf(stdin,"%d",&search);

	result = BinarySearch(0,(num - 1),array,search);
	if(result == -1)
		fprintf(stdout,"The element %d is not present in the array\n",search);
    else
		fprintf(stdout,"The element %d is in position %d\n",search,result);

	free(array);
	return 0;
}
Ejemplo n.º 22
0
// It should never be the case that more than one hash prefixes match a given
// full hash. However, if that happens, this method returns any one of them.
// It does not guarantee which one of those will be returned.
nsresult
VariableLengthPrefixSet::Matches(const nsACString& aFullHash, uint32_t* aLength)
{
  MutexAutoLock lock(mLock);

  // Only allow full-length hash to check if match any of the prefix
  MOZ_ASSERT(aFullHash.Length() == COMPLETE_SIZE);
  NS_ENSURE_ARG_POINTER(aLength);

  *aLength = 0;

  // Check if it matches 4-bytes prefixSet first
  const uint32_t* hash = reinterpret_cast<const uint32_t*>(aFullHash.BeginReading());
  uint32_t value = BigEndian::readUint32(hash);

  bool found = false;
  nsresult rv = mFixedPrefixSet->Contains(value, &found);
  NS_ENSURE_SUCCESS(rv, rv);

  if (found) {
    *aLength = PREFIX_SIZE_FIXED;
    return NS_OK;
  }

  for (auto iter = mVLPrefixSet.ConstIter(); !iter.Done(); iter.Next()) {
    if (BinarySearch(aFullHash, *iter.Data(), iter.Key())) {
      *aLength = iter.Key();
      MOZ_ASSERT(*aLength > 4);
      return NS_OK;
    }
  }

  return NS_OK;
}
Ejemplo n.º 23
0
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  
 * =====================================================================================
 */
    int
main (  )
{
    int n, i, key, position;
    int *array;
    printf("请输入有序数组的大小:");
    scanf("%d", &n);
    array = (int*)malloc(sizeof(int)*n);
    printf("请按升序输入数据:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d", &array[i]);
    }

    printf("请输入想要查找的数:\n");
    scanf("%d", &key);
    if(position = BinarySearch(array, key, 0, n-1))
    {
        printf("%d的位置为:%d\n", key, position);
    }
    else
    {
        printf("%d不存在.\n");
    }
    return 0;
}		/* -----  end of function main  ----- */
Ejemplo n.º 24
0
/*! \brief Calibration function
*
* Performs the calibration according to calibration method chosen.
* Compares different calibration results in order to achieve optimal results.
*
*/
void CalibrateInternalRc(void)
{
  unsigned int count;

#ifdef CALIBRATION_METHOD_SIMPLE                    // Simple search method
  unsigned char cycles = 0x80;

  do{
    count = Counter();
    if (count > countVal)
      OSCCAL--;                                     // If count is more than count value corresponding to the given frequency:
    NOP();                                          // - decrease speed
    if (count < countVal)
      OSCCAL++;
    NOP();                                          // If count is less: - increase speed
    if (count == countVal)
      cycles=1;			
  } while(--cycles);                                // Calibrate using 128(0x80) calibration cycles

#else                                               // Binary search with or without neighbor search
  unsigned char countDiff;
  unsigned char neighborSearchStatus = FINISHED;

  while(calibration == RUNNING){
    count = Counter();                              // Counter returns the count value after external ticks on XTAL
    if (calStep != 0)
    {
      BinarySearch(count);                          // Do binary search until stepsize is zero
    }
    else
    {
      if(neighborSearchStatus == RUNNING)
      {
        countDiff = ABS((signed int)count-(signed int)countVal);
        if (countDiff < bestCountDiff)                          // Store OSCCAL if higher accuracy is achieved
        {
          bestCountDiff = countDiff;
          bestOSCCAL = OSCCAL;
        }
        NeighborSearch();                                       // Do neighbor search
      }
      else                                                      // Prepare and start neighbor search
      {
#ifdef CALIBRATION_METHOD_BINARY_WITHOUT_NEIGHBOR               // No neighbor search if deselected
        calibration = FINISHED;
        countDiff = ABS((signed int)count-(signed int)countVal);
        bestCountDiff = countDiff;
        bestOSCCAL = OSCCAL;
#else
        neighborSearchStatus = RUNNING;                         // Do neighbor search by default
        neighborsSearched = 0;
        countDiff = ABS((signed int)count-(signed int)countVal);
        bestCountDiff = countDiff;
        bestOSCCAL = OSCCAL;
#endif
      }
    }
  }
#endif
}
Ejemplo n.º 25
0
void Puzzle2DNA::Mutate() {
	std::vector<float> copyValidDNA = m_validPieces;

	for (size_t i = 0; i < m_bin1.size(); i++) {
		auto it = m_bin1.begin() + i;
		if (!BinarySearch(copyValidDNA, it)) {
            m_bin1.erase(it);
			i--;
		}
	}

	for (size_t i = 0; i < m_bin2.size(); i++) {
		auto it = m_bin2.begin() + i;
		if (!BinarySearch(copyValidDNA, it)) {
            m_bin2.erase(it);
			i--;
		}
	}

	for (size_t i = 0; i < m_bin3.size(); i++) {
		auto it = m_bin3.begin() + i;
		if (!BinarySearch(copyValidDNA, it)) {
            m_bin3.erase(it);
			i--;
		}
	}
	// could add extra mutate here
	int newDNA;
	if (copyValidDNA.size() > 0) {
		while (m_bin1.size() < 10) {
			newDNA = rand() % copyValidDNA.size();
			m_bin1.push_back(copyValidDNA[newDNA]);
		}
	}
	if (copyValidDNA.size() > 0) {
		while (m_bin2.size() < 10) {
			newDNA = rand() % copyValidDNA.size();
			m_bin2.push_back(copyValidDNA[newDNA]);
		}
	}
	if (copyValidDNA.size() > 0) {
		while (m_bin3.size() < 10) {
			newDNA = rand() % copyValidDNA.size();
			m_bin3.push_back(copyValidDNA[newDNA]);
		}
	}
}
Ejemplo n.º 26
0
bool Pessoa::hasAluguer(Aluguer* al) //verifica se a pessoa tem o aluguer al activo
{
	int pos = BinarySearch(alugueres, *al);

	if (pos != -1)
		return true;
	return false;
}
int main(){
    int A[] = {2,4,5,7,13,14,15,23};
    printf("Enter a number: ");
    int x; scanf("%d",&x);
    int index = BinarySearch(A,0,8,x);
    if(index != -1) printf("Number %d is at index %d",x,index);
    else printf("Number %d not found",x);
}
Ejemplo n.º 28
0
/* Checks to see if the type of entity is to be output
 */
static int IsValidEntType(char *type)

{
    if (BinarySearch(type, 0, options.entTypesCount - 1,
                    options.entTypes) >= 0)
        return TRUE;
    return False;
}
Ejemplo n.º 29
0
// -----------------------------------------------------------------------------
bool Algorithms::Test_BinarySearch()
{
    bool pass = true;

    {
        int a[] = {};
        std::vector<int> v = vec_transform(a, sizeof(a) / sizeof(int));
        pass = pass && (BinarySearch(v, 0) == KEY_NOT_FOUND);
    }

    {
        int a[] = {1};
        std::vector<int> v = vec_transform(a, sizeof(a) / sizeof(int));
        pass = pass && (BinarySearch(v, 0) == KEY_NOT_FOUND) &&
            (BinarySearch(v, 1) == 0)
            ;
    }

    {
        int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        std::vector<int> v = vec_transform(a, sizeof(a) / sizeof(int));
        pass = pass && (BinarySearch(v, 0) == KEY_NOT_FOUND)
            && (BinarySearch(v, 1) == 0)
            && (BinarySearch(v, 9) == 8)
            && (BinarySearch(v, 5) == 4)
            ;
    }

    return pass;
}
Ejemplo n.º 30
0
int main() {
    int arr[10] = {1, 3, 5, 11, 12, 13, 17, 22, 25, 28}; // Sorted
    for(int i = 0; i < 10; i++) {
        std::cout << "arr[" << i << "] = "<< arr[i] << std::endl;
    }
    int key = 22;
    std::cout << "key : " << key << std::endl;
    std::cout << "ans : " << BinarySearch(arr, key, 0, 9) << std::endl;
}