C language inserts a number into an ordered array so that the new array is still ordered Case explanation

Let's look at an example first:

There is an array that has been sorted. After requiring a number to be entered, it is inserted into the array according to the original sorting rule.

Idea analysis

1) This array is an ordered array. Ascending and descending order are not mentioned in the question , we assume that this ordered array is in ascending order (numbers are sorted from small to large).

2) If the number to be inserted is smaller than any number in the array, put it in the first position of the array, and the rest of the numbers in the array are moved backwards to form a new array; if the number to be inserted is smaller than If any number in the array is too large, put it in the next position of the last digit of the array, and the position of the number in the array remains unchanged to form a new array; if the number to be inserted is to be inserted in the array, find the first one If it is a larger number, put it in the position of the first number larger than it, and the position of the first number larger than it and the number positions after the first number larger than it are moved backward by one bit to form a new array.

for example:

Insert 38 into the ordered array arr[6]={11,22,33,44,55};, through observation, it can be directly concluded that 38 should be inserted in front of 44 to form a new ordered array, but the computer I don’t know, he will only loop through the array to find the first number 44 that is greater than 38, then put 38 in the position of 44, and then move 44 and the numbers after 44 backward to form a new array.

Take inserting 38, 0, and 60 into the ordered array arr[6]={11,22,33,44,55} as an example to write the code.

The case code is as follows

#include <stdio.h>
#define  N 6
void main(){
	int arr[N]={11,22,33,44,55};
	int a;
	int i,j=0;
	printf("请输入要插入的数\n");
	scanf("%d",&a);
	for(i=0;i<N;i++){
		if(arr[i]>a){
			j=i;//j记录第一个比插入数字大的数字位置
			break;//如果插入的数要放在数组第一个位置上,j为0;
			      //如果插入的数要放在数组里面,j<N;
		}
		else{
			j+=1;//如果插入的数要放在数组最后一个数字的后面,j为N;
		}
	}
	if(j==0){//如果插入的数字小于数组的所有数字,就把他放在数组的第一个位置上,j是0
       for(i=N;i>=j;i--){
	    arr[i+1]=arr[i];//把数组里大于插入数字的数字都向后移动一个位置
	}
	   arr[j]=a;//插入的数字要放的位置,下面代码块的arr[j]=a;同理
	}
	else if(j<N){//如果插入的数字要插在数组里,j<n
		for(i=N;i>=j;i--){
	     arr[i+1]=arr[i];//把数组里大于插入数字的数字都向后移动一个位置
	}
		arr[j]=a;
	}
	else if(j==N){//如果插入的数要放在数组最后一个数字的后面,j为N;
		arr[N-1]=a;数组最后一个数字后面的位置下角标为N-1
	}
	printf("新的有序数组如下\n");
	for(i=0;i<N;i++){
	    printf("%d\t",arr[i]);
	}//打印输出插入数字的有序数组,
}

The case code is as follows

38 insert into the array

0 is inserted into the array

60 inserted into the array

Guess you like

Origin blog.csdn.net/weixin_63279307/article/details/130062859