Tuesday, April 2, 2013

Java: Positive Number Array

/*
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.

*/

 

  1. public class PositiveNumberArray {

  2. /**

  3. * @param args

  4. */

  5. public static void main(String[] args) {

  6. // TODO Auto-generated method stub

  7. int a[] = {3,5,6,30,-3,-3,-3,5,3,-3};

  8. for(int i : retainPositiveNumbers(a))

  9. System.out.println(i);

  10. }


  11. public static int[] retainPositiveNumbers(int[] a) {

  12. /*

  13. Please implement this method to

  14. return a new array with only positive numbers from the given array.

  15. The elements in the resulting array shall be sorted in the ascending order.


  16. */


  17. int len=0;

  18. int b[];

  19. for(int i=0;i<a.length;i++)

  20. {

  21. if(a[i]>0)

  22. len++;

  23. }



  24. b = new int[len];

  25. for(int i=0,j=0;i<a.length;i++)

  26. {

  27. if(a[i]>0)

  28. {

  29. b[j]=a[i];

  30. j++;

  31. }

  32. }


  33. int temp;

  34. for(int i=0;i<b.length-1;i++)

  35. {

  36. for(int j=i+1;j<b.length;j++)

  37. {

  38. if(b[j]<b[i])

  39. {

  40. temp=b[j];

  41. b[j]=b[i];

  42. b[i]=temp;

  43. }

  44. }


  45. }


  46. return b;

  47. }

  48. }


Download Link: Click Here

0 comments: