Transform array in java.

 Given an array with N distinct all are positive elements, convert the given array to a form where all elements are in the range from 0 to N-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, … N-1 is placed for the largest element.

 import java.util.Scanner;

public class code
{
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("enter size of array=");
    int n=sc.nextInt();
    int[] arr=new int[n];
    System.out.println("enter elements of array=");
    for(int i=0; i<n; i++){
        arr[i]=sc.nextInt();
    }
    int x=0;
    for(int i=0; i<n; i++){
        int min=Integer.MAX_VALUE;
        int index=-1;
        for(int j=0; j<n; j++){
            if(arr[j]<min && arr[j]>0){
                min=arr[j];
                index=j;
            }
        }
        arr[index]=x;
        x--;
    }

    System.out.println("transform array is=");
    for(int ele : arr){
        System.out.print(-1*ele+" ");
    }
}
}

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.