Sort by

recency

|

1469 Discussions

|

  • + 0 comments

    Hello! I tried to not use the native sorting function, to really exercise the coding. Since it's a tutorial with the purpose of practicing the language, I've implemented the quicksort:

        let lastIndex = nums.length - 1;
        let sortedNums = quickSort(nums, 0, lastIndex);
        let largest = sortedNums[lastIndex];
        let secondLargest;
        for(let x = lastIndex; x >= 0; x--) {
            if (largest === sortedNums[x])
                continue;
            else {
                secondLargest = sortedNums[x];
                break;
            }         
        }
        return secondLargest;
    }
    function partition(arr, low, high) {
            let pivot = arr[high];
            let i = low - 1; 
            for(let j = low; j <= high-1; j++){
                if(pivot > arr[j]){              
                    i++;                
                    swap(arr, i, j);   
                }
            }
            
            swap(arr, i+1, high); 
            return i+1; 
    }
    function quickSort(arr, low, high) {
            if (high > low) {
                let pi = partition(arr, low, high);
                quickSort(arr, low, pi - 1); 
                quickSort(arr, pi+1, high); 
            } 
            return arr;
    }   
    function swap(arr, i, j) {
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
    }
    
  • + 0 comments

    function getSecondLargest(nums) { // Complete the function let sortedNums = Array.from(new Set(nums)).sort((a, b) => (b-a));

    //sorted nums;
    return sortedNums[1];
    

    }

  • + 0 comments
    function getSecondLargest(nums) {
        const uniqueNums = nums.filter((value, idx, self)=> self.indexOf(value) === idx);
        return uniqueNums.sort((a,b)=>b-a)[1];
    }
    
  • + 0 comments

    THIS IS MINE

    function getSecondLargest(nums) {
        return Array.from(new Set(nums)).sort((a, b) => b - a) [1];
    }
    
  • + 2 comments
    function getSecondLargest(nums) {
        const uniqueNums = [...new Set(nums)];
        uniqueNums.sort((a, b) => b - a);
        return uniqueNums[1];
    }