optimized bubble sort javascript

Solutions on MaxInterview for optimized bubble sort javascript by the best coders in the world

showing results for - "optimized bubble sort javascript"
Ronnie
19 Apr 2018
1const optimizedBubbleSort = (arr) => {
2  let hasSwapped = false;
3  let outerLoopIterationCount = 0;
4  
5  for (let i = 0; i < arr.length; i++) {
6    for (let j = 0; j < arr.length - i; j++) {
7      if (arr[j] > arr[j + 1]) {
8        hasSwapped = true;
9        let tmp = arr[j];
10        arr[j] = arr[j + 1];
11        arr[j + 1] = tmp;
12      }
13    }
14    if (!hasSwapped) {
15      return outerLoopIterationCount;
16    } else {
17      hasSwapped = false;
18    }
19    outerLoopIterationCount++;
20  }
21  return outerLoopIterationCount;
22}