Wiggle Sort (Wave Sort)
Reorders array to a0 ≤ a1 ≥ a2 ≤ a3 … using a single pass of local swaps.
Visualization
Interactive visualization for Wiggle Sort (Wave Sort)
Wiggle Sort Visualization
Sort array into wave pattern: a[0] ≤ a[1] ≥ a[2] ≤ a[3] ≥ a[4] ≤ ...
Pattern Check:
Time Complexity: O(n) - single pass
Space Complexity: O(1) - in-place
How it works:
- For even index i: ensure arr[i] ≤ arr[i+1]
- For odd index i: ensure arr[i] ≥ arr[i+1]
- Swap if condition violated
- Creates wave/zigzag pattern
- Used in waveform generation, signal processing
Interactive visualization with step-by-step execution
Implementation
1function wiggleSort(arr: number[]): number[] {
2 const a = [...arr];
3 for (let i = 1; i < a.length; i++) {
4 if ((i % 2 === 1 && a[i] < a[i-1]) || (i % 2 === 0 && a[i] > a[i-1])) {
5 [a[i], a[i-1]] = [a[i-1], a[i]];
6 }
7 }
8 return a;
9}Deep Dive
Theoretical Foundation
Ensure alternating ≤ and ≥ by swapping adjacent elements whenever the local condition is violated at each index.
Complexity
Time
O(n)
O(n)
O(n)
Space
O(1)
Applications
Industry Use
Wave-like visualization
Local alternation constraints
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.