C++ algorithm foundation (4)--array element inversion algorithm

This article continues to explain the knowledge of algorithms. Today, I will talk about the algorithm for reversing array elements. Although there are ready-made wrapper functions, it is necessary to understand its ideas.

1. Problem needs

Enter a set of numbers and reverse the position of this set of numbers.
Example: Enter 123, the result is 321
Insert picture description here

2. Code implementation

int main()
{
	int a[10]={0};
	int n;
	int temp;
	int i;
	cout<<"请输入数组大小:"<<endl;
	scanf("%d",&n);
	cout<<"请输入数组元素:"<<endl;
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	for(int i=0;i<n/2;i++)
	{
		temp=a[i];
		a[i]=a[n-i-1];
		a[n-i-1]=temp;
	}
	cout<<"数组反转后:"<<endl;
	for(i=0;i<n;i++)
	{
		printf("%d",a[i]);
	}
	cout<<"\n"<<endl;
	return 0;
}

Result:
Insert picture description here
Analysis:
1. First of all, to reverse the elements in the array, it must be inverted once every two elements. Therefore, a total of the array size needs to be reversed /2 times.
2. During the first reversal, the first element of the array is swapped with the last element of the array, and for the second reversal, the second element of the array is swapped with the last element of the array at position -1. Therefore, it can be summarized as the following expression

for(int i=0;i<n/2;i++)
{
	temp=a[i];//定义中间变量temp赋值a[i]
	a[i]=a[n-i-1];//数组第一个元素换为最后一个元素
	a[n-i-1]=temp;//数组最后一个元素换为第一个元素
}

Example: Input 3,3,1,2, the steps are:
1. When i=0, temp=a[0]=3, a[0]=a[3]=2, a[3]=temp= 3. The result of the first swap is 2,3,1,3.
2. When i=1, temp=a[1]=3, a[1]=a[2]=1, a[2]=temp=3, the result of the second exchange is 2,1,3 ,3.
The result is the result of the demonstration.

Three. Thinking, convert array characters

int main()
{
	char a[10]={NULL,};
	int n;
	char temp;
	int i;
	cout<<"请输入数组大小:"<<endl;
	scanf("%d",&n);
	cout<<"请输入数组元素:"<<endl;
	for(i=0;i<n;i++)
	{
		scanf("%s",&a[i]);
	}
	for(int i=0;i<n/2;i++)
	{
		temp=a[i];
		a[i]=a[n-i-1];
		a[n-i-1]=temp;
	}
	cout<<"数组反转后:"<<endl;
	for(i=0;i<n;i++)
	{
		printf("%c",a[i]);
	}
	cout<<"\n"<<endl;
	return 0;
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/baidu_41191295/article/details/111710785
Recommended