skip to Main Content

I want to create a JavaScript Function that sorts numbers from maximum to minimum without using the traditional .sort() method

const sortArray= (array)=>{
    let newArray = []
    let firstArray = array[0]
    for(const num in array){
        if(num>firstArray){
         firstArray = num
         newArray.push(firstArray)
        }else{
         firstArray = firstArray
         newArray.push(firstArray)
        }
    }
   return newArray
}
console.log(sortArray([0,10,-1,4,7]))

But the code is not sorting properly. I don’t know I missed or added wrong.

2

Answers


  1. A selection sort algorithm to efficiently find and swap elements, resulting in the array sorted from highest to lowest.

    const sortArray = (array) => {
      let newArray = [];
    
      for (let i = 0; i < array.length; i++) {
        let maxIndex = i;
    
        // Find the index of the maximum element within the remaining unsorted part
        for (let j = i + 1; j < array.length; j++) {
          if (array[j] > array[maxIndex]) {
            maxIndex = j;
          }
        }
    
        // Swap the current element with the maximum element
        [array[i], array[maxIndex]] = [array[maxIndex], array[i]];
      }
      return array;
    };
    
    console.log(sortArray([0, 10, -1, 4, 7])); // Output: [10, 7, 4, 0, -1]
    Login or Signup to reply.
  2. You can create a new sorted array by inserting elements with binary search:

    const sortArray = array => {
        const out = [array[0]];
        for (let i = 1; i < array.length; i++) {
            let mid, v = array[i], low = 0, high = out.length;
            while (low <= high) {
                mid = (low + high) / 2 | 0;
                if (mid === out.length || v === out[mid]) break;
                v < out[mid] ? low = mid + 1 : high = mid - 1;
            }
            out.splice(Math.max(low, mid), 0, v);
        }
        return out;
    }
    const arr = Array.from({ length: 100 }, () => Math.random() * 100 | 0);
    console.log(...sortArray(arr));
    ` Chrome/121
    -------------------------------------------------------------------------------
    >                n=100      |     n=1000     |     n=10000     |    n=100000   
    Alexander   1.00x x100k 246 | 1.00x x10k 624 |  1.00x x100 130 |  1.00x x1  130
    Ermi        1.25x x100k 307 | 3.77x  x1k 235 | 17.00x  x10 221 | 17.31x x1 2250
    -------------------------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    const $chunk = () => Array.from({ length: 100 }, () => Math.random() * 100 | 0);
    const $input =[];
    
    // @benchmark Alexander
    const sortArray = array => {
        const out = [array[0]];
        for (let i = 1; i < array.length; i++) {
            let mid, v = array[i], low = 0, high = out.length;
            while (low <= high) {
                mid = (low + high) / 2 | 0;
                if (mid === out.length || v === out[mid]) break;
                v < out[mid] ? low = mid + 1 : high = mid - 1;
            }
            out.splice(Math.max(low, mid), 0, v);
        }
        return out;
    }
    // @run
    sortArray($input);
    
    // @benchmark Ermi
    const sortArray2 = (array) => {
      let newArray = [];
    
      for (let i = 0; i < array.length; i++) {
        let maxIndex = i;
    
        // Find the index of the maximum element within the remaining unsorted part
        for (let j = i + 1; j < array.length; j++) {
          if (array[j] > array[maxIndex]) {
            maxIndex = j;
          }
        }
    
        // Swap the current element with the maximum element
        [array[i], array[maxIndex]] = [array[maxIndex], array[i]];
      }
      return array;
    };
    //@run 
    sortArray2($input);
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search