Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Non Zero shift

import java.io.*;
import java.util.*;

/*
 * Problem Statement : Shift all 0's to left in time complexity O(n)
 */

public class NonZeroShift {
  public static void main(String[] args) {
    int[] input = {6,4,0,5,0,0,1,6};

    System.out.println("Input array is : ");
    for (int i : input) {
      System.out.print(i+" ");
    }
    System.out.println();
    
       
    int[] output = sortNonZero(input);
    
    System.out.println("New array is : ");    
   for (int i : output) {
      System.out.print(i+" ");
    }
    
  }
  
  private static int[] sortNonZero(int[] input){
    int temp = -1;
    for(int i =input.length-1; i > -1; i--){
      if(input[i] == 0 && temp ==-1){
        temp = i;
      }else if (temp != -1 && input[i] != 0){
        int temp1 = input[temp];
        input[temp] = input[i];
        input[i] = temp1;
        temp--;
      }
  }
    return input;
  } 
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.