Algorithm question: Find the position where a number appears in an array, and an array of numbers
// There is an int-type array, and the difference between each two adjacent numbers is not 1, that is, //-1. Given a number, we need to find the position of this number in the array. # Include <iostream> using namespace std; void Grial (int a [], int n, int val) {// my idea is to start with the first number, if the number is 2, // and the number I want to find is 5, then it is better that I have to jump to the back and jump to the position 5-2 = 3, because each number only differs by 1 or-1. int I = 0; int * B = new int [n]; // if all values are val, n space is required. Int k = 0; for (; I <n;) {if (a [I] = val) {B [k ++] = I; I ++ ;} else {int len = a [I]> val? A [I]-val: val-a [I]; I + = len ;}} cout <val <"The subscript position displayed is :"; for (I = 0; I <k; I ++) {cout <B [I] <";}cout <endl ;}int main () {int a [] = {2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 3, 4, 5}; Grial (a, sizeof (a)/sizeof (int ), 5); return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.