寫一個程式來接受一個由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中文網其他相關文章!