在单个数组中对两半执行操作的 C 程序
问题
编写一个程序来接受一个由N 个元素组成的一维数组并分成两半。稍后,将前半部分按升序排序,将后半部分按降序排序。
解决方案
下面解释了在 C 编程语言中对单个数组中的两半执行两个操作的解决方案 -
用于按升序对前半部分进行排序的逻辑如下-
for (i=0; i<b; ++i){for (j=i+1; j<b; ++j){
if (number[i] > number[j]){
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
用于按降序对后半部分进行排序的逻辑如下 -
for (i=b; i<n; ++i){for (j=i+1; j<n; ++j){
if (number[i] < number[j]){
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
用于将数组分成两半并相应打印的逻辑如下 -
上半场升序
for (i=0; i<b; ++i)printf ("%d ",number[i]);
下半场降序
for(i=b;i<n;i++)printf("%d ",number[i]);
示例
以下是对单个数组中的两半执行两个操作的 C 程序-
#include<stdio.h>输出结果void main(){
int i,j,a,n,b,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
b = n/2;
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<b; ++i){
for (j=i+1; j<b; ++j){
if (number[i] > number[j]){
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
for (i=b; i<n; ++i){
for (j=i+1; j<n; ++j){
if (number[i] < number[j]){
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf (" The 1st half numbers\n");
printf (" arranged in asc\n");
for (i=0; i<b; ++i)
printf ("%d ",number[i]);
printf("\nThe 2nd half Numbers\n");
printf("order arranged in desc.order\n");
for(i=b;i<n;i++)
printf("%d ",number[i]);
}
执行上述程序时,会产生以下结果 -
Enter the value of N10
Enter the numbers
20
34
23
11
45
56
78
98
76
54
The 1st half numbers
arranged in asc
11 20 23 34 45
The 2nd half Numbers
order arranged in desc.order
98 78 76 56 54
以上是 在单个数组中对两半执行操作的 C 程序 的全部内容, 来源链接: utcz.com/z/322684.html