Please implement this method to
return a new array with only positive numbers from the given array.
The elements in the resulting array shall be sorted in the ascending order.
*/
- public class PositiveNumberArray {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int a[] = {3,5,6,30,-3,-3,-3,5,3,-3};
- for(int i : retainPositiveNumbers(a))
- System.out.println(i);
- }
- public static int[] retainPositiveNumbers(int[] a) {
- /*
- Please implement this method to
- return a new array with only positive numbers from the given array.
- The elements in the resulting array shall be sorted in the ascending order.
- */
- int len=0;
- int b[];
- for(int i=0;i<a.length;i++)
- {
- if(a[i]>0)
- len++;
- }
- b = new int[len];
- for(int i=0,j=0;i<a.length;i++)
- {
- if(a[i]>0)
- {
- b[j]=a[i];
- j++;
- }
- }
- int temp;
- for(int i=0;i<b.length-1;i++)
- {
- for(int j=i+1;j<b.length;j++)
- {
- if(b[j]<b[i])
- {
- temp=b[j];
- b[j]=b[i];
- b[i]=temp;
- }
- }
- }
- return b;
- }
- }
Download Link: Click Here

0 comments:
Post a Comment