//have an array of int, the difference between each two consecutive numbers is not 1//-1. Now given a number, it is required to find the position of the number in the array. #include <iostream>using namespace STD;voidGrial (intA[],intNintVal) {//My train of thought is starting from the first number, if this number is 2, //And the number I'm looking for is 5, so the best I have to go back //Jump 5-2=3 positions, because each number only differs by 1 or -1. inti =0;int*b =New int[n];//If All is Val, then n space is required. intK =0; for(; i < n;) {if(A[i] = = val) {b[k++] = i; i++; }Else{intLen = A[i]>val? A[i]-val:val-a[i]; i + = Len; } }cout<< Val <<"The following locations appear:"; for(i=0; I < K; i++) {cout<< B[i] <<" "; }cout<< Endl;}intMain () {intA[] = {2,3,4,5,6,7,6,5,4,3,2,1,2,3,4,5}; Grial (A,sizeof(a)/sizeof(int),5);return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm title: Find the position of a number in an array