Descending selection sort in JavaScript I wrote a simple sort algorithm in JavaScript, but code climate is complaining its complexity being too high (currently sitting on 6 instead of 5, which is code climate wants).

I personally cannot see how it can be further simplified. 

Can anyone help? The following algorithm sorts an array of numbers from largest to smallest.

function selectionSort(array) {
    let index = 0;
    let terminatingIndex = array.length - 1;
    let nextElementIndex = null;

    while (index &lt; terminatingIndex) {
        nextElementIndex = index + 1;
        while (nextElementIndex &lt;= terminatingIndex) {
            if (array[index] &lt; array[nextElementIndex]) {
                [array[index], array[nextElementIndex]] = [array[nextElementIndex], array[index]];
            }
            nextElementIndex++;
        }
        index++;
    }
    console.log(`The sorted array is: ${array}`);
}
I think the problem could be, that your algorithm isn't exactly a selection sort but rater a bubble sort. They are very similar, but where bubble sort swaps every two elements when the left is smaller than the right (descending order), selection sort defers swapping to after the inner loop is finished and then only swaps the last found candidate with the index'th element.

To accomplish that in your algorithm, you can modify it as follows:

function selectionSort(array) {
  let index = 0;
  let length = array.length;
  let nextElementIndex = 0;

  while (index &lt; length - 1) {
    nextElementIndex = index + 1;

    let maxIndex = index; // This will hold the index of the possible last candidate for swapping.

    while (nextElementIndex &lt; length) {
      if (array[maxIndex ] &lt; array[nextElementIndex]) {
        // Instead of swapping here, only the index of the candidate is saved.
        maxIndex = nextElementIndex;
      }
      nextElementIndex++;
    }

    // And finally: if any element to the right of index is greater than the element at index then swap.
    if (maxIndex != index) {
      [array[index], array[maxIndex ]] = [array[maxIndex ], array[index]];
    }

    index++;
  }
}




A suggestion that may improve readability could be to use for-loops instead of while -loops