cocktail sort javascript

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

showing results for - "cocktail sort javascript"
Lorenzo
17 Feb 2017
1function cocktailSort(arr) {
2  let left = 0;
3  let right = arr.length - 1;
4  let hasSwapped = false;
5  let outerLoopIterationCount = 0;
6
7  while (left < right) {
8    outerLoopIterationCount++;
9    for (let i = left; i < right; i++) {
10      if (arr[i] > arr[i + 1]) {
11        swap(arr, i, i + 1);
12        hasSwapped = true;
13      }
14    }
15    right--;
16    for (let i = right; i > left; i--) {
17      if (arr[i] < arr[i - 1]) {
18        swap(arr, i, i - 1);
19        hasSwapped = true;
20      }
21    }
22    left++;
23    if (!hasSwapped) {
24      return outerLoopIterationCount;
25    } else {
26      hasSwapped = false;
27    }
28  }
29  return outerLoopIterationCount;
30}