Wednesday, 4 July 2012

sort an array a[n] containing 0s and 1s with time complexity n and you cant use more than 1 data structure



// TIME: O(n) || Space : O(1)
#include<stdio.h> int main() { int A[20],i,j,n,temp; printf("Enter n :"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&A[i]); printf("\n--"); i=0; j=n-1; while(i<j) { while(A[i]==0) i++; while(A[j]==1) j--; if(i<j) { temp=A[i]; A[i]=A[j]; A[j]=temp; i++; j--; } }// end of while printf("\n"); for(i=0;i<n;i++) printf("%d ",A[i]); printf("\n"); return 0; }

No comments:

Post a Comment