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+1];
                number[j+1] = number[k]-number[j+1];
                number[k] = number[k]-number[j+1];  
                k = j+1;
                }else if(number[j+1]>=0){
                    k = j+1;
                }
        }
        
        } 
        System.out.print("After Sorting : ");
        for(int i=0; i<number.length; i++){
            System.out.print(number[i]+" "); 
        }

Output:
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

Comments

Popular posts from this blog

BEA-000362 Server failed. Reason: [Management:141268]Parsing Failure in config.xml

Oracle OIM - Search and Update Organization using java API

Trim Leading and Trailing spaces from InputText on tab out.