Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array` [-1,150,190,170,-1,-1,160,180]. I need to sort this array, but without moving the numbers -1, so it will return [-1,150,160,170,-1,-1,180,190].How can i do that?

What I have tried:

I have tried like this`

function solution(x){	
	var arr = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] != -1){
			arr.push(x[i]);
		}
	}
	arr = arr.sort(function(a,b){return a-b});
	var arr2 = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] == -1){
			arr2.push(x[i]);
		}
		else{
			arr2.push(?);
		}
	}
	return arr2;
}
console.log(solution([-1,150,190,170,-1,-1,180,160]));
Posted
Updated 17-Aug-18 10:05am
v5

1 solution

This is how I would see it:
JavaScript
In= [-1,150,190,170,-1,-1,160,180];
// here you build a filtered array without the -1 numbers
Filtered= [150,190,170,160,180];
// here do a normal sort
Sorted= [150,160,170,180,190];
// here build the Out array by merging the -1 from In and the values from Sorted
Out= [-1,150,160,170,-1,-1,180,190];

[Update]
Good start, now you need to build out array with respect to positions of -1 in original
JavaScript
function solution(x){	
	var arr = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] != -1){
			arr.push(x[i]);
		}
	}
	arr = arr.sort(function(a,b){return a-b});
	// here you need to build out array
	// Just like you filtered x earlier, you need to loop again in x
	// when you encounter a -1, push it in out array
	// otherwise get next value from arr
	return arr;
}
console.log(solution([-1,150,190,170,-1,-1,180,160]));
 
Share this answer
 
v3
Comments
Suren97 17-Aug-18 14:34pm    
So i can filter array and remove only -1, then sort that array. but then how can i put -1 numbers after sorting?
Patrice T 17-Aug-18 14:39pm    
No, you create a new array which you populate with non -1 values, you don't touch to original array.
Suren97 17-Aug-18 14:42pm    
What do you mean? :(
Suren97 17-Aug-18 14:47pm    
Look, I updated my solution, do you mean like this?
Suren97 17-Aug-18 14:49pm    
In this case i got sorted array, but now how can i fill -1 numbers in it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900