Skip to content

Instantly share code, notes, and snippets.

@yamamaya
Created December 17, 2025 20:04
Show Gist options
  • Select an option

  • Save yamamaya/877a754421f1f3b0868b59550f077ac1 to your computer and use it in GitHub Desktop.

Select an option

Save yamamaya/877a754421f1f3b0868b59550f077ac1 to your computer and use it in GitHub Desktop.
Get median from 9 elements by sorting network.
#define SWAP(a, b) if (arr[a] > arr[b]) { uint8_t tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; }
uint8_t Median9(uint8_t arr[9]) {
SWAP(0, 1);
SWAP(1, 2);
SWAP(0, 1);
SWAP(3, 4);
SWAP(4, 5);
SWAP(3, 4);
SWAP(6, 7);
SWAP(7, 8);
SWAP(6, 7);
SWAP(0, 3);
SWAP(3, 6);
SWAP(0, 3);
SWAP(1, 4);
SWAP(4, 7);
SWAP(1, 4);
SWAP(2, 5);
SWAP(5, 8);
SWAP(2, 5);
SWAP(2, 4);
SWAP(4, 6);
SWAP(2, 4);
return arr[4];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment