C language learning notes - sorting and searching

1. Introduction of sorting algorithm

Sorting is also called sort algorithm. Sorting is the process of arranging a group of data in a specified order

1.1 classification of sorting

(1) Internal sorting: refers to loading all data to be processed into internal memory (memory) for sorting

(2) External sorting: the amount of data is too large to be loaded into memory, so it needs to be sorted with the help of external storage

1.2 bubble sorting

1.2.1 introduction to bubble sorting

The basic idea of Bubble Sorting is to compare the values of adjacent elements from front to back (starting from the elements with smaller subscripts) through the sequence to be sorted, and exchange if the reverse order is found, so as to gradually move the elements with larger values from front to back

Five unordered numbers: {3, 9, - 1, 10, - 2} are arranged into an ordered sequence from small to large by bubble sorting

1.2.2 code example of bubble sorting

The user outputs a sequence and arranges it into an ordered sequence from small to large by bubble sorting

#include<stdio.h>
void main() {
	int arr[10], i, strLen, j ,temp;
	strLen = sizeof(arr) / sizeof(int);
	for (i = 0; i < strLen; i++) {
		printf("Please enter a number:");
		scanf_s("%d", &arr[i]);
	}
	for (j = 0; j < strLen - 1; j++) {//The outer loop is used to control the number of rounds traversed
		for (i = 0; i < strLen - 1 - j; i++) {//The inner loop is used to control the number of rounds
			if (arr[i] > arr[i + 1]) {
				temp = arr[i];//If the array element to be traversed this time is larger than the next element to be traversed
				arr[i] = arr[i + 1];//The values of the two elements are exchanged through the temp variable
				arr[i + 1] = temp;
			}
		}
	}
	for (i = 0; i < strLen; i++) {//Output the bubble sorted array in turn
		printf("%d\t", arr[i]);
	}
}

2. Find

2.1. Find introduction

In C, there are two common Searches:

  1. Sequential search
  2. Binary search

2.2. Find code examples

  1. 1. There is a number sequence: {23, 1, 34, 89101} guessing game: enter a number arbitrarily from the keyboard to judge whether the number is included in the number sequence [sequential search] requirements: if it is found, it will prompt to find it and give the subscript value. If it is not found, there will be no prompt.

    #include<stdio.h>
    void main() {
    	int num, i, j = 0;
    	int arr[5] = { 23, 1, 34, 89, 101 };
    	printf("Please enter the number you want to find:");
    	scanf_s("%d", &num);
    	for (i = 0; i < sizeof(arr) / sizeof(int); i++) {//Traverses the array in order
    		if (num == arr[i]) {//Determine whether the elements of the array traversed each time are equal to this number
    			j = 1;//If a number is found, change the value of j to 1 to judge whether a number is found later
    			break;
    		}
    	}
    	if (j == 1) {
    		printf("The number you are looking for is in the array, and the subscript is%d", i);
    	}
    	else{
    		printf("The number you are looking for is not in the array");
    	}
    }
    

  2. Please enter an ordered array for binary search, and enter a number to see if this number exists in the array, and find the subscript. If not, you will be prompted with "no this number". The premise of binary search is that the array is an ordered array

    #include<stdio.h>
    int find(int low, int high, int num, int arr[]) {
    	int mid;
    	for (mid = (low + high) / 2; low <= high;) {
    		if (arr[mid] == num) {//If the array element pointed to by mid is consistent with the number to be found
    			return mid;//return mid returns its subscript
    		}
    		else if (arr[mid] > num) {//If the array element pointed to by mid is larger than the number to find
    			high = mid - 1;//It means that the number to be found is smaller than the array element pointed to by midmid, and its interval should be on the left of mid
    			mid = (low + high) / 2;//Therefore, high points to mid - 1
    		}//This enables you to continue searching to the left of the mid
    		else if (arr[mid] < num) {//If the array element pointed to by mid is less than the number to find
    			low = mid + 1;//It means that the number to be found is larger than the array element pointed to by midmid, and its interval should be on the right of mid
    			mid = (low + high) / 2;//Therefore, mid points to mid + 1
    		} // This enables you to continue searching on the right side of the mid
    	}
    	return -1;//If the for loop does not return mid exit, it means it is not found. After execution, return -1 means it is not found
    }
    void main() {
    	int arr[7], i, num;
    	for (i = 0; i < sizeof(arr) / sizeof(int); i++) {
    		printf("Please enter a number:");
    		scanf_s("%d", &arr[i]);
    	}
    	printf("Please enter the number you want to find:");
    	scanf_s("%d", &num);
    	i = find(0, 6, num, arr);
    	if (i != -1) {
    		printf("The number you are looking for is in the sequence, and its subscript is%d", i);
    	}
    	else {
    		printf("The number you are looking for is not in the sequence");
    	}
    }

3. Two dimensional array

3.1. Two dimensional array code example

Please output the following graphics with a two-dimensional array

0 0 0 0 0 0

0 0 1 0 0 0

0 2 0 3 0 0

0 0 0 0 0 0

#include<stdio.h>
void main() {
	int arr[4][6], i, j;
	for (i = 0; i < 4; i++) {//Traverse the array through the for loop and assign 0 to the array elements one by one
		for (j = 0; j < 6; j++) {
			arr[i][j] = 0;
		}
	}
	arr[2][1] = 2;
	arr[2][3] = 3;
	arr[1][2] = 1;
	for (i = 0; i < 4; i++) {
		for (j = 0; j < 6; j++) {
			printf("%d ", arr[i][j]);
		}
		printf("\n");
	}
}

  1. First, through the traversal of the array (in the first for loop, the outer for loop is row traversal and the inner for loop is column traversal), assign the array elements to 0 one by one
  2. After that, some elements are assigned specific values through a single array element assignment
  3. The essence of two-dimensional array in computer is still a bit array, and its address is on the address of the previous element ➕ Unit size of 1 array element (if it is an array of type int, then ➕ 4; If it is of type double, then ➕ 8; If char type ➕ 1, and so on)

3.2. How to use two-dimensional arrays

  1. Type array name[size][size] = {{Value 1,Value 2..},{Value 1,Value 2..},{Value 1,Value 2..}};
  2. Type array name[size][size] = { Value 1,Value 2,Value 3,Value 4,Value 5,Value 6 ..};

3.3. Two dimensional array exercises

  1. int arr[3][2]={{4,6},{1,4},{-2,8}}; Traverse the two-dimensional array and get and
    //int arr[3][2] = { {4,6},{1,4},{-2,8} };  Traverse the two-dimensional array and get and
    #include<stdio.h>
    void main() {
    	int arr[3][2] = { {4,6},{1,4},{-2,8} };
    	int i, j, sum = 0;
    	for (i = 0; i < 3; i++) {//Row traversal
    		for (j = 0; j < 2; j++) {//Column traversal
    			sum += arr[i][j];//Set a variable to record the sum of the elements of each variable
    		}
    	}
    	printf("The sum of all elements of the array is%d", sum);
    }

  2. Define a two-dimensional array, which is used to save the scores of three classes and five students in each class, and calculate the average score of each class and the average score of all classes

    //Define a two-dimensional array, which is used to save the scores of three classes and five students in each class, and calculate the average score of each class and the average score of all classes
    #include<stdio.h>
    void main() {
    	double arrScore[3][5], score = 0.0, classScore = 0.0, totalScore = 0.0;
    	int i, j;
    	for (i = 0; i < 3; i++) {//Row traversal
    		printf("\n");
    		for (j = 0; j < 5; j++) {//Column traversal
    			printf("Please enter%d class%d Grade of classmate No", i +1, j + 1);
    			scanf_s("%lf", &arrScore[i][j]);//Store scores in an array
    		}
    	}
    	for (i = 0; i < 3; i++) {
    		classScore = 0.0;//You need to reset the classScore to zero before each column traversal
    		for (j = 0; j < 5; j++) {
    			printf("\n%d class%d The grade of classmate No. is:%.2f", i + 1, j + 1, arrScore[i][j]);
    			classScore += arrScore[i][j];//Get the total score of the class
    		}
    		totalScore += classScore;//Get the total score after each column traversal
    		classScore /= 5;//Get the average grade of the class
    		printf("\n%d The average score of the class is:%.2f: ", i + 1, classScore);
    	}
    	totalScore /= 15;//Get a full GPa
    	printf("\n The average score of all classes is:%.2f", totalScore);
    }

3.4. Details and precautions of using two-dimensional array

  1. You can only assign values to some elements, and the unassigned elements will automatically take the "zero" value
    #include<stdio.h>
    void main() {
    	int arr[2][3] = { {1}, {2} }, i, j;
    	for (i = 0; i < 2; i++) {
    		for (j = 0; j < 3; j++) {
    			printf("%d\t", arr[i][j]);
    		}
    		printf("\n");
    	}
    }

  2. If all elements are assigned values, the length of the first dimension may not be given

    #include<stdio.h>
    void main() {
    	int arr[][3] = { 1, 2, 3, 4, 5, 6}, i, j;
    	for (i = 0; i < 2; i++) {
    		for (j = 0; j < 3; j++) {
    			printf("%d\t", arr[i][j]);
    		}
    		printf("\n");
    	}
    }

  3. Two dimensional arrays can be regarded as nested by one-dimensional arrays; If each element of an array is an array, it is a two-dimensional array. For example, a two-dimensional array a[3][4] can be regarded as three one-dimensional arrays. Their array names are a[0], a[1] and a[2]. These three one-dimensional arrays have four elements. For example, the elements of one-dimensional array a[0] are a[0][0], a[0][1], a[0][2] and a[0][3]

Keywords: C C++ C# Back-end

Added by Zay on Fri, 14 Jan 2022 03:18:21 +0200