C++ Programming Lesson 16: Expandable Knowledge Points of One-Dimensional Arrays (Finding Extremes, Sorting, and Searching)

🚀 C++ Programming Lesson 16: Expandable Knowledge Points of One-Dimensional Arrays (Finding Extremes, Sorting, and Searching)

C++ Programming Lesson 16: Expandable Knowledge Points of One-Dimensional Arrays (Finding Extremes, Sorting, and Searching)

📚 Course Navigation

1、🤔 Why Learn Array Expansion Operations? 2、🌟 Finding Extremes in Arrays: Finding Maximum / Minimum Values (Core Logic and Practical Cases)3、⚡ Simple Array Sorting: Bubble Sort and Selection Sort 4、🧩 Value-Based Search in Arrays: Finding the Index of Corresponding Elements (Exact Search and Fuzzy Judgment)5、📦 Comprehensive Case: Processing Array Data with Multiple Operations (Solving Complex Real Problems)6、⚠️ Common Errors in Expansion Operations (Pitfall Guide to Avoid Logical Flaws)7、📢 Next Lesson Preview: Detailed Explanation of do-while Loop (A New Looping Method that Executes Before Judgment)

1. 🤔 Why Learn Array Expansion Operations? — From “Usable” to “Useful”

Previously, we learned to traverse arrays and dynamically assign values, enabling us to “store data” and “access data one by one”. However, in practical scenarios, we need to perform more “in-depth processing” on array data:

  • 📊 When analyzing student grades, we need to “find the highest score” to determine the number of full scores;
  • 🛒 When organizing product prices, we need to “sort by price from low to high” for user convenience;
  • 🔍 When managing employee IDs, we need to “search for corresponding employee information based on the ID”.

These scenarios require “expansion operations” on arrays — finding extremes, sorting, and searching. Mastering these operations allows arrays to transform from “simple storage containers” into “tools that solve real problems”, truly realizing the value of arrays.

2. 🌟 Finding Extremes in Arrays: Finding Maximum / Minimum Values

The core logic for finding extremes in arrays is to “assume an initial extreme value, then traverse the array to compare and update”. It’s like “when selecting a class leader, first tentatively choosing a candidate, then comparing with others, and the more outstanding person becomes the new candidate”.

(1) Core Steps (Taking Finding Maximum as an Example)

  1. Assume Initial Maximum Value: Take the first element of the array (arr[0]) as the initial maximum value (maxVal);
  1. Traverse the Array for Comparison: Starting from the second element (arr[1]), compare each with maxVal;
  1. Update Maximum Value: If the current element is greater than maxVal, update maxVal to the current element;
  1. End of Traversal: maxVal is the maximum value of the array.

The logic for finding the minimum value is exactly the same, just set the initial value to arr[0] and look for “smaller elements” during comparison.

(2) Code Implementation: Finding Maximum and Minimum Values in an Array

Requirement: Define an int array, find the maximum and minimum values in the array, and output them.

#include <iostream>
using namespace std;
int main() {
	int numbers[] = {15, 7, 22, 9, 30, 5};
	int length = sizeof(numbers) / sizeof(int);
	// 1. Assume initial extreme value (first element of the array)
	int maxVal = numbers[0];
	int minVal = numbers[0];
	// 2. Traverse the array (starting from the second element, index 1)
	for (int i = 1; i < length; i++) {
		// Update maximum value
		if (numbers[i] > maxVal) {
			maxVal = numbers[i];
		}
		// Update minimum value
		if (numbers[i] < minVal) {
			minVal = numbers[i];
		}
	}
	// 3. Output results
	cout << "The maximum value in the array is: " << maxVal << endl;  // Output 30
	cout << "The minimum value in the array is: " << minVal << endl;  // Output 5
	return 0;
}

(3) Practical Case: Finding Extremes with Dynamic Assignment

Requirement: Allow the user to input 8 integers, dynamically store them in an array, and find the maximum value among them.

#include <iostream>
using namespace std;
int main() {
	const int SIZE = 8;
	int arr[SIZE];
	// 1. Dynamic assignment: User inputs 8 integers
	cout << "Please enter 8 integers:" << endl;
	for (int i = 0; i < SIZE; i++) {
		cout << "The " << (i + 1) << "th integer:";
		cin >> arr[i];
	}
	// 2. Find maximum value
	int maxVal = arr[0];
	for (int i = 1; i < SIZE; i++) {
		if (arr[i] > maxVal) {
			maxVal = arr[i];
		}
	}
	cout << "The maximum value among the 8 integers you entered is: " << maxVal << endl;
	return 0;
}

Running Scenario:

Enter 8 integers:
The 1th integer: 12
The 2th integer: 45
The 3th integer: 23
The 4th integer: 56
The 5th integer: 7
The 6th integer: 34
The 7th integer: 67
The 8th integer: 28
The maximum value among the 8 integers you entered is: 67

3. ⚡ Simple Array Sorting: Bubble Sort and Selection Sort

Sorting is one of the most common operations on arrays, which involves “rearranging array elements in a certain order (from smallest to largest / from largest to smallest)”. Here we will explain two beginner-level sorting algorithms: Bubble Sort and Selection Sort, which have simple logic and are suitable for beginners to master.

(1) Bubble Sort: “Compare Adjacent Elements, Larger Ones Sink to the Back”

The core logic is like “bubbles rising from the bottom of the water”. Each time we traverse the array, we compare two adjacent elements and push the larger one “backward”. After multiple traversals, the largest element will gradually “sink” to the end of the array, ultimately achieving sorting.

Code Implementation: Bubble Sort (From Smallest to Largest)

#include <iostream>
using namespace std;
int main() {
	int scores[] = {85, 72, 93, 68, 98, 88};
	int length = sizeof(scores) / sizeof(int);
	// Bubble sort core: outer loop controls "sorting rounds", inner loop controls "comparison times per round"
	for (int i = 0; i < length - 1; i++) {  // Rounds: length elements need length-1 rounds
		for (int j = 0; j < length - 1 - i; j++) {  // Comparison times per round: more rounds mean fewer comparisons
			// Compare adjacent elements, if front is larger than back, swap (sort from smallest to largest)
			if (scores[j] > scores[j + 1]) {
				// Swap the values of the two elements (using a temporary variable temp)
				int temp = scores[j];
				scores[j] = scores[j + 1];
				scores[j + 1] = temp;
			}
		}
	}
	// Output sorted array
	cout << "After bubble sort (from smallest to largest):";
	for (int i = 0; i < length; i++) {
		cout << scores[i] << " ";
	}
	return 0;
}

Running Result:

After bubble sort (from smallest to largest): 68 72 85 88 93 98

(2) Selection Sort: “Find the Minimum Element and Place it at the Front”

The core logic is to find the “minimum value of the unsorted part” each time we traverse the array and swap it with the “first element of the unsorted part”, gradually “selecting” the minimum value to the front of the array, ultimately achieving sorting.

Code Implementation: Selection Sort (From Smallest to Largest)

#include <iostream>
using namespace std;
int main() {
	int prices[] = {29, 58, 15, 36, 42};
	int length = sizeof(prices) / sizeof(int);
	// Selection sort core: outer loop controls "starting position of the unsorted part"
	for (int i = 0; i < length - 1; i++) {
		// 1. Assume the first element of the unsorted part is the minimum value, record its index
		int minIndex = i;
		// 2. Traverse the unsorted part to find the true minimum value index
		for (int j = i + 1; j < length; j++) {
			if (prices[j] < prices[minIndex]) {
				minIndex = j;  // Update minimum value index
			}
		}
		// 3. Swap the minimum value with the first element of the unsorted part
		if (minIndex != i) {  // Only swap if the minimum value is not the current element
			int temp = prices[i];
			prices[i] = prices[minIndex];
			prices[minIndex] = temp;
		}
	}
	// Output sorted array
	cout << "After selection sort (from smallest to largest):";
	for (int i = 0; i < length; i++) {
		cout << prices[i] << " ";
	}
	return 0;
}

Running Result:

After selection sort (from smallest to largest): 15 29 36 42 58

4. 🧩 Value-Based Search in Arrays: Finding the Index of Corresponding Elements

Value-based search is to “find the corresponding element in the array based on a given target value and return its index”, just like “finding a phone number in a contact list based on a name”. If there are multiple identical target values in the array, it usually returns “the index of the first matching element”.

(1) Core Steps

  1. Traverse the Array: Access each array element one by one;
  1. Compare with Target Value: Check if the current element equals the target value;
  1. Return Index: If a matching element is found, immediately return its index;
  1. Search Failure: If traversal ends without finding, return a special value (like -1, indicating “not found”).

(2) Code Implementation: Finding Element Index by Value

Requirement: Define an int array, allow the user to input a target value, and search for its index in the array (if not found, prompt “not found”).

#include <iostream>
using namespace std;
int main() {
	int ids[] = {101, 102, 103, 104, 105};
	int length = sizeof(ids) / sizeof(int);
	int target, index = -1;  // index initialized to -1 (indicating not found)
	// 1. User inputs target value
	cout << "Please enter the employee ID to search:";
	cin >> target;
	// 2. Traverse the array to find the target value
	for (int i = 0; i < length; i++) {
		if (ids[i] == target) {
			index = i;  // Record index of the target value found
			break;  // Exit loop immediately after finding to improve efficiency
		}
	}
	// 3. Output search result
	if (index != -1) {
		cout << "Found target value " << target << ", corresponding index is: " << index << endl;
	} else {
		cout << "Target value " << target << " not found" << endl;
	}
	return 0;
}

Running Scenario 1 (Found Target Value):

Enter the employee ID to search: 103
Found target value 103, corresponding index is: 2

Running Scenario 2 (Not Found Target Value):

Enter the employee ID to search: 106
Target value 106 not found

5. 📦 Comprehensive Case: Combining Multiple Array Operations (Dynamic Assignment + Sorting + Finding Extremes)

Requirement: Allow the user to input 6 students’ English scores, dynamically store them in an array, sort them from high to low, find the highest and lowest scores, and finally output the sorted scores, highest score, and lowest score.

#include <iostream>
using namespace std;
int main() {
	const int STUDENT_NUM = 6;
	int scores[STUDENT_NUM];
	// 1. Dynamic assignment: User inputs 6 scores
	cout << "Please enter 6 students' English scores:" << endl;
	for (int i = 0; i < STUDENT_NUM; i++) {
		cout << "The " << (i + 1) << "th student's score:";
		cin >> scores[i];
	}
	// 2. Bubble sort (from high to low)
	for (int i = 0; i < STUDENT_NUM - 1; i++) {
		for (int j = 0; j < STUDENT_NUM - 1 - i; j++) {
			if (scores[j] < scores[j + 1]) {  // Swap if front is smaller than back (from high to low)
				int temp = scores[j];
				scores[j] = scores[j + 1];
				scores[j + 1] = temp;
			}
		}
	}
	// 3. Find highest and lowest scores (after sorting, the first element is the highest, the last is the lowest)
	int maxScore = scores[0];
	int minScore = scores[STUDENT_NUM - 1];
	// 4. Output results
	cout << "\nSorted scores (from high to low):";
	for (int i = 0; i < STUDENT_NUM; i++) {
		cout << scores[i] << " ";
	}
	cout << "\nHighest score: " << maxScore << endl;
	cout << "Lowest score: " << minScore << endl;
	return 0;
}

Running Result:

Enter 6 students' English scores:
The 1th student's score: 82
The 2th student's score: 95
The 3th student's score: 78
The 4th student's score: 100
The 5th student's score: 88
The 6th student's score: 92
Sorted scores (from high to low): 100 95 92 88 82 78
Highest score: 100
Lowest score: 78

6. ⚠️ Common Errors in Expansion Operations

Error 1: Setting Initial Value to 0 When Finding Extremes (Instead of the First Element of the Array)

If all elements in the array are negative (e.g., {-5, -3, -8}), setting the initial value to 0 will lead to incorrect maximum value judgment:

// Error: Initial value set to 0, when the array is all negative, 0 will be considered the maximum value
int maxVal = 0;
for (int i = 0; i < length; i++) {
	if (arr[i] > maxVal) maxVal = arr[i];  // Final maxVal=0, not -3
}

✅ Correct: The initial value must be set to the first element of the array (arr[0]) to ensure coverage of all element cases.

Error 2: Incorrect Inner Loop Condition in Bubble Sort (Not Reducing by Rounds i)

// Error: Inner loop condition not reducing i, causing already sorted elements to be compared repeatedly
for (int j = 0; j < length - 1; j++) {  // The last i rounds of elements are sorted, no need to compare again, which wastes efficiency and may cause errors
}

✅ Correct: The inner loop condition should be written as j < length – 1 – i, reducing comparison times each round.

Error 3: Not Handling the Case of “Multiple Identical Elements” When Searching for Elements

If there are multiple identical target values in the array (e.g., {10, 20, 10, 30}), the default is to return only the index of the first matching element. If you need to return all indices, you must remove the break:

// Find indices of all identical elements
for (int i = 0; i < length; i++) {
	if (arr[i] == target) {
		cout << "Found target value, index: " << i << endl;  // Do not break, continue searching
	}
}

7. 📢 Next Lesson Preview: Detailed Explanation of do-while Loop (A New Looping Method that Executes Before Judgment)

In this lesson, we have mastered the operations of finding extremes, sorting, and searching in arrays, enabling us to flexibly handle array data. Next, we will learn a new loop structure —do-while Loop.

The biggest difference between it and the while loop we learned before is:while loop “judges before executing”, which may not execute even once; while do-while loop “executes before judging”, ensuring at least one execution. This feature is particularly suitable for scenarios that require “performing an operation once before judging whether to continue”:

  • 🎮 Game Scenario: “Let the player play a game once, then ask if they want to continue playing”;
  • 📝 Input Validation: “Let the user input a password first, then check if the password is correct; if not, prompt for re-entry”.

In the next lesson, we will learn:

1. The syntax structure and execution principle of do-while loop;2. The differences between do-while and while loops (when to use do-while);3. Practical cases of do-while loop (input validation, simple game loop).

Once you master the do-while loop, you will be able to handle more scenarios that require “executing once first”, making loops

C++ Programming Lesson 16: Expandable Knowledge Points of One-Dimensional Arrays (Finding Extremes, Sorting, and Searching)

Leave a Comment