Posts

Showing posts from 2019

Sort the array without changing the position of negative numbers

Problem: Given an array arr[] of N integers, the task is to sort the array without changing  the position of negative numbers (if any) i.e. the negative numbers need not be sorted. Example: Before Sorting : 2 -6 -3 -8 5 -18 0 8 4 6 1 -11 After Sorting : 0 -6 -3 -8 1 -18 2 4 5 6 8 -11         int[] number = {2, -6, -3, -8, 5, -18, 0, 8, 4, 6, 1, -11};         System.out.print("Before Sorting : ");         for(int i=0; i<number.length; i++){             System.out.print(number[i]+" ");          }         System.out.println("");         //Looping over arry to sort the number         for(int i=0; i<number.length-1; i++){             //Swapping two values if first value is grater than the second value.             int k = 0;             for(int j=0;j<number.length-i-1;j++){                 if((number[k] >= number[j+1]) && (number[k] >= 0) && (number[j+1]>=0)){                 number[k] = number[k]+number[j

Print equilateral triangle in java

Below prints Equilateral Triangle. public class PrintEqulateralTriangle {     public static void main(String[] args) {         int numberOfRow = 10;         int numberOfStars = numberOfRow + (numberOfRow - 1);         int median = (numberOfStars+1)/2;         for(int i=1; i<=numberOfRow; i++){             int start = (i==1 ? median : (median - i + 1));             int end = (i==1 ? median : (median + i - 1));             for(int j=1; j<=end;j++){                 if((j>= start) && (j <= end)){                 System.out.print("* ");                 }else{                 System.out.print("  ");                 }             }            System.out.println();         }     } } Output: --------                            *                         * * *                      * * * * *                   * * * * * * *                * * * * * * * * *             * * * * * * * * * * *          * * * * * * * * * * * * *  

Print Right Angle Triagle in Java

Below prints right angle triangle. public class PrintRightAngleTriangle {     public static void main(String[] args) {                for(int i=0; i<=10 ; i++){             for(int j=0;j<=i;j++){                 System.out.print("* ");             }             System.out.println();         }     } } Output: -------- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *