1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| class AlgorithmUtils { public: static int binarySearch(const vector<int>& arr, int target) { int left = 0, right = static_cast<int>(arr.size()) - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } static void quickSort(vector<int>& arr, int low, int high) { if (low < high) { int pivot = partition(arr, low, high); quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } static int findSubstring(const string& text, const string& pattern) { if (pattern.empty()) return 0; if (text.length() < pattern.length()) return -1; for (size_t i = 0; i <= text.length() - pattern.length(); i++) { size_t j = 0; while (j < pattern.length() && text[i + j] == pattern[j]) { j++; } if (j == pattern.length()) { return static_cast<int>(i); } } return -1; } static long long calculateSum(const vector<int>& arr) { long long sum = 0; for (const int& element : arr) { sum += element; } return sum; } static pair<int, int> findMinMax(const vector<int>& arr) { if (arr.empty()) { throw invalid_argument("Array is empty"); } int minVal = arr[0], maxVal = arr[0]; for (const int& element : arr) { if (element < minVal) minVal = element; if (element > maxVal) maxVal = element; } return make_pair(minVal, maxVal); }
private: static int partition(vector<int>& arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return i + 1; } };
void exercise4() { cout << "\n=== 练习4:const优化的算法实现 ===" << endl; vector<int> numbers = {64, 34, 25, 12, 22, 11, 90, 5}; cout << "原始数组: "; for (const int& num : numbers) { cout << num << " "; } cout << endl; cout << "数组和: " << AlgorithmUtils::calculateSum(numbers) << endl; auto minMax = AlgorithmUtils::findMinMax(numbers); cout << "最小值: " << minMax.first << ", 最大值: " << minMax.second << endl; AlgorithmUtils::quickSort(numbers, 0, static_cast<int>(numbers.size()) - 1); cout << "排序后: "; for (const int& num : numbers) { cout << num << " "; } cout << endl; int target = 25; int index = AlgorithmUtils::binarySearch(numbers, target); cout << "查找 " << target << ": " << (index != -1 ? "找到,索引 " + to_string(index) : "未找到") << endl; string text = "Hello World, this is a test string"; string pattern = "World"; int pos = AlgorithmUtils::findSubstring(text, pattern); cout << "在 \"" << text << "\" 中查找 \"" << pattern << "\": "; cout << (pos != -1 ? "找到,位置 " + to_string(pos) : "未找到") << endl; }
|