ajayg415 / Javascript-Algorithms

1 stars 0 forks source link

Problem: Sort the unsorted Array #14

Closed ajayg415 closed 3 years ago

ajayg415 commented 4 years ago

We have one unsorted array with duplication. Write a logic to sort the array like below.

Input =  [1, 5, 2, 1, 5, 2, 3, 5, 5, 1];

Output = [1,2,3,5,1,2,5,1,5];

hint: [[1,2,3,5],[1,2,5],[1,5]]
msreddy09 commented 4 years ago
var resTempArr = []
var count = 0;
var arr = [1, 5, 2, 1, 5, 2, 3, 5, 5, 1];
var sortedArr = arr.sort((a,b) => a-b)
for(var i = 0; i< sortedArr.length;i++){
 if(sortedArr[i]== sortedArr[i-1]){
    count++;
    if(!resTempArr[count]) 
       resTempArr[count] = []
    resTempArr[count].push(sortedArr[i])    
 }
 if(sortedArr[i]!= sortedArr[i-1]){
     count = 0;
     if(!resTempArr[count]) 
        resTempArr[count] = []
     resTempArr[count].push(sortedArr[i])
  }
}
console.log(resTempArr.flat())
ajayg415 commented 3 years ago

https://github.com/ajayg415/Javascript-Algorithms/tree/04e0a2d3fef34ee8a623b4a5f6d069d536487dc0