-
题目要求:设任意n个整数存放于数组A(1:n)中,试编写程序,将所有正数排在所有负数前面。
-
排序代码
void Adjust(int a[],int n) { int low=0,high=n-1; int temp; while(low<high) { while(low<high&&a[low]>0)low++; while(low<high&&a[high]<0)high--; if(low<high&&a[low]<0) { temp=a[low]; a[low]=a[high]; a[high]=temp; } } }
-
完整程序
#include<stdio.h> void Adjust(int a[],int n) { int low=0,high=n-1; int temp; while(low<high) { while(low<high&&a[low]>0)low++; while(low<high&&a[high]<0)high--; if(low<high&&a[low]<0) { temp=a[low]; a[low]=a[high]; a[high]=temp; } } } void Traverse(int a[],int n) { for(int i=0;i<n;i++) { printf("%d ",a[i]); } } int main() { int a[]={1,-1,2,-2,3,-3,4,-4}; Traverse(a,8); printf("\n"); Adjust(a,8); Traverse(a,8); }
设任意n个整数存放于数组A(1:n)中,试编写程序,将所有正数排在所有负数前面。
于 2021-11-10 19:42:38 首次发布