Ransomware poses a severe threat to cybersecurity, with its capacity to encrypt critical data and demand ransoms causing significant financial and operational damage to individuals and organizations alike. The hierarchical K-nearest neighbors (KNN) algorithm, proposed in this study, offers a novel and significant approach to ransomware detection by leveraging hierarchical relationships within opcode sequences to achieve more granular and precise classification. The methodology involves collecting opcode sequences from diverse ransomware and benign software samples, preprocessing the data through normalization, feature extraction, and dimensionality reduction, and applying a multi-level hierarchical KNN algorithm. Experimental results indicate that the hierarchical KNN algorithm outperforms traditional machine learning models in terms of detection accuracy, computational efficiency, and robustness to noise. The algorithm's scalability and moderate memory usage make it suitable for deployment in resource-constrained environments, highlighting its potential for practical applications in real-world cybersecurity scenarios. This research contributes a significant advancement in the field of ransomware detection, demonstrating the efficacy of hierarchical classification techniques in addressing the complexities of modern cyber threats.