Cyclic Sort Visualization

Speed:
Step: 0 / -1
Algorithm Code
1function cyclicSort(arr) {
2    // Cyclic sort works well for arrays containing 1 to n values
3    const n = arr.length;
4    
5    // Traverse array elements
6    let i = 0;
7    while (i < n) {
8      // Find the correct position (index) for the current element
9      // For an array with values 1 to n, the correct position is value-1
10      const correctPos = arr[i] - 1;
11      
12      // If the element is not at its correct position
13      if (arr[i] !== arr[correctPos]) {
14        // Swap with the element at the correct position
15        [arr[i], arr[correctPos]] = [arr[correctPos], arr[i]];
16      } else {
17        // Element is at its correct position, move to next element
18        i++;
19      }
20    }
21    
22    return arr;
23  }
Visualization