This tutorial explains in detail how routing works.
Take a scenario where two PC’s are connected to a switch. The IP address of PC1 and PC2 is 192.168.1.2 and 192.168.1.3 respectively. The subnet masks of the PC’s are 255.255.255.0. From the IP address and subnet mask , the network address is 192.168.1.0. This implies that both the PC’s reside on the same network. If PC1 wishes to communicate with PC2, an additional device like a router is not required, since both the devices reside on the same network.
Consider the above scenario where the IP address of PC1 and PC2 is 192.168.1.2 and 192.168.2.2 respectively. The subnet mask for both the PC’s are 255.255.255.0. The network address of PC1 and PC2 is 192.168.1.0 and 192.168.2.0 respectively. This implies that both the PC’s are on different networks. If PC1 needs to send data to PC2, the IP packet carrying the data has to be sent through a device which is capable of understanding different networks like a router. This process is termed as routing.
In the first case, the switch does not understand the concept of different networks since basically
a switch works at layer 2 of the OSI model whereas routers work at layer 3 of the OSI model.