How were the colors selected kind of depends on why there are only 16 of them.
In short, a CGA monitor takes four bit RGBI color input which means 16 colors. Each RGB color bit turns an electron gun for that color and I bit adds intensity to all of the guns, and brown color is handled with an exception.
A color monitor has three electron guns for three color phosphors, and those color are red, green and blue. So if each color is simply turned on or off, you need three bits to control the electron guns, which allows for 8 colors. Black color is all guns off, white is all guns on. The three colors with single gun on are red, green and blue. The three colors with two guns on are cyan, magenta and yellow.
For each character cell in the color text mode, the CGA reserves one full byte for character code and one full byte for 8-bit character attributes.
If there had been 2 color bits per gun in the monitor (which is what EGA does), it would use 6 bits for 64 colors - too much to store. It would also make sense to still have more colors than 8, so the attribute byte was used to have 4 bits of foreground color and 4 bits for background color. This then left one bit for each color gun and one extra bit for intensity, so it was enough to have 4 colour bits allowing for 16 different colors. So three bits control the guns separately and one bit adds brightness to all of them.
There is one special mechanism to alter the color palette in the monitor. There is bright yellow, but no dark yellow. The bit pattern for dark yellow is special and the analog voltages for driving the electron guns are altered to produce brown instead. This basically means that the DAC or color lookup table to convert bit patterns of color values to analog video voltages is in the CGA monitor that takes digital 4-bit RGBI input.
Another special mechanism was implemented in the CGA card which affects text mode background color selection. The fourth background attribute bit functionality is selectable. By default it controls if the foreground color blinks or not, so only the 8 dark background colors are available for selection. It can be changed to control the background intensity bit, which allows for selecting all 16 background colors, but then blinking text is not possible.
Explanation how the color order is determined from RGBI bits controlling the electron guns:
X = IRGB bits = color
0 = 0000 = Black
1 = 0001 = Blue (Dark)
2 = 0010 = Green (Dark)
3 = 0011 = Cyan (Dark)
4 = 0100 = Red (Dark)
5 = 0101 = Magenta (Dark)
6 = 0110 = Brown (actually, Dark Yellow which is adjusted to Brown in monitor)
7 = 0111 = White (actually, Dark White, Gray, Bright Gray, Light Gray)
8 = 1000 = Gray (actually, Dark Gray, Bright Black, Intensity Black)
9 = 1001 = Blue (Bright)
A = 1010 = Green (Bright)
B = 1011 = Cyan (Bright)
C = 1100 = Red (Bright)
D = 1101 = Magenta (Bright, or Pink)
E = 1110 = Yellow (Bright)
F = 1111 = White (Bright)