【数组二分查找+数组反转】2022-11-19
缘由在数组 a 中用折半查找法查找一个数,若找到,显示其在数组中的位置。若找不到,提示“No found!”。-编程语言-CSDN问答
已知数组 a 为{1,6,9,12,14,18,19,22,25,27,29,30,35,36,39},在数组 a 中用折半查找法查找一个数,若找到,显示其在数组中的位置。若找不到,提示“No found!”。要求编写自定义函数 int srch(int a[],int x,int left,int right)函数,该函数用折半查找法在数组 a 中指定的下标范围内 left 和 right 之间查找 x,若找到,返回数组所在的下标,否则返回-1。
void 数组反转(int* a, int n)
{int x = 0,t=0;z:if (x < n - x){ t = a[x] - a[n - 1 - x], a[x] -= t, a[n - 1 - x] += t, ++x; goto z; }
}
void 数组二分查找()
{//缘由https://ask.csdn.net/questions/7839788int a[]{1, 6, 9, 12, 14, 18, 19, 22, 25, 27, 29, 30, 35, 36, 39}, x = 0, n = 15, j = 0;bool k = 1;//std::cin >> x;数组反转(a, n); k = 0;y:if (++x<40){std::cout << x << ":";j = --n;c:if (n>0){if (a[j] == x || a[j - 1] == x)goto js;else if (a[j] > x)k ? j -= n /= 2 : j += n /= 2;else if (a[j] < x)k ? j += n /= 2 : j -= n /= 2;else;if (n>1 && n % 2)++n; else;goto c;}js:n = 15;if (a[j] == x)std::cout << j << "\n";else if (a[j - 1] == x)std::cout << --j << "\n";else if (a[j + 1] == x)std::cout << ++j << "\n";elsestd::cout << "No found!\n";goto y;}
}
