Sensor nodes (SNs), which are low-power devices with short network lifetimes and efficient energy use, make up a wireless sensor network (WSN). A wireless device runs on batteries and uses a base station (BS) to send sensed data to the end user. WSNs are particularly prone to anomalies due to their complicated properties. Anomalies are abnormal data measurements obtained from sensors in a network for a range of factors, including faulty sensors or resource constraints such as computing capabilities, energy, or even faulty sensor communication systems. The main goal of the proposed algorithm is to develop an energy-efficient routing algorithm that can detect abnormalities in the environment and extend the network's stability period and lifespan. There have been three distinct anomaly detection methods used: random forest, K-nearest neighbour (KNN), and local outlier factor (LOF). In the proposed work, the heterogeneous network has been classified into two regions based on sensor location and the node’s energy level to overcome load and power distribution issues. In the first region, the nodes participate in the clustering process, and for efficient cluster heads (CHs) selection, an objective function called Node Performance Score (NPS) has been introduced, whereas in the other region, relay nodes have been established for efficient data collection to enhance the network lifespan. The LOF-based anomaly detection routing algorithm improved by 258%, 250%, and 62.15% over LEACH, SEP, and ZSEP in the stability period. The KNN-based anomaly detection routing algorithm improved by 259%, 250.68%, and 62.47% over LEACH, SEP, and ZSEP in the stability period. The random forest-based anomaly detection routing algorithm improved by 246.40%, 237.78%, and 56.50% over LEACH, SEP, and ZSEP in the stability period. © The Author(s), under exclusive licence to Springer Nature Singapore Pte Ltd. 2024.