Posts

Showing posts from December, 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