Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.*;
  2. import java.lang.*;
  3. public class Javaexcercise
  4. {
  5. public static void main (String[] args)
  6. {
  7. int nums[] = {1,1,0,1,0,1,1,1,0,0,0};
  8. int nums_size = nums.length;
  9. int left = 0, right = nums_size - 1;
  10.  
  11. System.out.println("Original Array : "+Arrays.toString(nums));
  12.  
  13. while (left < right)
  14. {
  15.  
  16. while (nums[left] == 0 && left < right)
  17. left++;
  18.  
  19. while (nums[right] == 1 && left < right)
  20. right--;
  21.  
  22.  
  23. if (left < right)
  24. {
  25. nums[left] = 0;
  26. nums[right] = 1;
  27. left++;
  28. right--;
  29. }
  30. }
  31.  
  32. System.out.println("Array after segregation is : "+Arrays.toString(nums));
  33. }
  34. }

Result

java techstudy.org

     





Related Topics




Popular Posts