编写一个程序来接受一个由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</p><p>"); scanf ("%d", &n); b = n/2; printf ("Enter the numbers </p><p>"); 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</p><p>"); printf (" arranged in asc</p><p>"); for (i=0; i<b; ++i) printf ("%d ",number[i]); printf("</p><p>The 2nd half Numbers</p><p>"); printf("order arranged in desc.order</p><p>"); for(i=b;i<n;i++) printf("%d ",number[i]); }
当执行上述程序时,会产生以下结果 -
Enter the value of N 10 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程序在一个单一数组上执行两个半部分的操作的详细内容。更多信息请关注PHP中文网其他相关文章!