Posted By

smundall on 02/07/16


Tagged


Versions (?)

Array Split


 / Published in: Java
 

Simple function for splitting array in half. Given X, we count the numbers that Match X beginning at 0. Next we count the odd numbers. If the odd numbers after X are greater than or equal to the number of even (matches) we return the array count to that point.

  1. //split array function . test 2
  2. public static int splitArray(int X, int[] A){
  3.  
  4. //declare our integers.
  5. int even = 0, odd = 0, i = 0;
  6.  
  7. //two while loops.
  8. while(i < A.length && A[i] == X) {
  9. ++even;
  10. ++i;
  11. }
  12. while(i < A.length && A[i] != X) {
  13. ++odd;
  14. ++i;
  15. }
  16.  
  17. if(odd >= even)
  18. return even * 2;
  19. else
  20. return 0;
  21.  
  22.  
  23. }

Report this snippet  

You need to login to post a comment.