fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int findAppIndex(int* appList, int appListSize, int targetAppName) {
  5. int left = 0;
  6. int right = appListSize - 1;
  7.  
  8. while (left <= right) {
  9. int mid = left + (right - left) / 2;
  10.  
  11. if (appList[mid] == targetAppName) {
  12. return mid;
  13. } else if (appList[mid] < targetAppName) {
  14. left = mid + 1;
  15. } else {
  16. right = mid - 1;
  17. }
  18. }
  19.  
  20. return -1;
  21. }
  22.  
  23. int main() {
  24. int appList[] = {0, 4, 6, 9, 13};
  25. int appListSize = sizeof(appList) / sizeof(appList[0]);
  26. int targetAppName = 6;
  27.  
  28. int index = findAppIndex(appList, appListSize, targetAppName);
  29.  
  30. if (index != -1) {
  31. cout << "目标应用编号 " << targetAppName << " 的下标为: " << index << endl;
  32. } else {
  33. cout << "目标应用编号 " << targetAppName << " 不存在" << endl;
  34. }
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
目标应用编号 6 的下标为: 2