---
title: "In a binary search, what exceptions can arise if the input array is not sorted?"  
description: "In a binary search, what exceptions can arise if the input array is not sorted?"  
author: "Revati S Misra"  
published: 2023-08-07  
updated: 2023-08-28  
canonical: https://www.mindstick.com/forum/159502/in-a-binary-search-what-exceptions-can-arise-if-the-input-array-is-not-sorted  
category: "data structure"  
tags: ["exception handling", "data structure", "binary search tree"]  
reading_time: 2 minutes  

---

# In a binary search, what exceptions can arise if the input array is not sorted?

In a [binary search](https://www.mindstick.com/forum/159485/working-of-a-binary-search-tree-bst-and-what-is-its-time-complexity-for-insertion-and-retrieval), what [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions) can arise if the [input](https://www.mindstick.com/forum/159209/how-can-i-read-convert-an-input-stream-into-a-string-in-java) [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net) is not sorted?

## Replies

### Reply by Aryan Kumar

If the input array is not sorted, then the [binary](https://www.mindstick.com/forum/34709/please-write-a-program-for-decimal-to-binary-conversion-in-c-sharp) [search](https://www.mindstick.com/articles/65368/best-smo-services-company-in-hyderabad-improve-search-rankings) algorithm may not be able to find the target element. This is because the binary search algorithm relies on the fact that the array is sorted in ascending order. If the array is not sorted, then the algorithm may not be able to narrow down the search space to the correct location of the target element.

Here are some specific exceptions that can arise if the input array is not sorted:

- The algorithm may not terminate. This is because the algorithm may keep looping forever, unable to find the target element.
- The algorithm may return the wrong element. This is because the algorithm may find an element that is smaller than the target element, but not the smallest element in the array.
- The algorithm may throw an exception. This is because the algorithm may try to divide by zero when calculating the middle index of the array.

To avoid these exceptions, it is important to ensure that the input array is sorted before using the binary search algorithm. This can be done using a sorting algorithm, such as bubble sort, selection sort, or merge sort.


---

Original Source: https://www.mindstick.com/forum/159502/in-a-binary-search-what-exceptions-can-arise-if-the-input-array-is-not-sorted

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
