# Sparse Search

> Given a sorted array of strings that is interspersed with empty strings, write a method to find the location o

- 作者：[小土刀](https://wdxtub.com/about)
- 发布日期：2016-01-10
- 原文（引用请使用此链接）：https://wdxtub.com/blog/interview/sparse-search
- 所属系列：interview 面试刷题笔记
- 标签：面试刷题、排序和搜索
- 许可：CC BY-NC-SA 4.0（https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh）
- 正文中的站内图片路径以 https://wdxtub.com 为根目录。

> 阅读提示：这是 2016 年前后整理的历史面试资料。面经与招聘信息仅代表当时情况，代码包含旧语言版本及未完成笔记；练习时请自行验证边界条件和运行结果。

---

## Sparse Search

Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string

EXAMPLE

Input:  ball, {at, ,, , ball,, , car,, , dad,, ""}  

Output: 4

### Solution

In case mid is an empty string. We simply move mid to the closest non-empty string

### Code

```java
int search(String[] strings, String str, int first, int last){
    if (first > last) return -1;
    int mid = (last + first) / 2;

    // If mid is empty, find closest non-empty string
    if (strings[mid].isEmpty()){
        int left = mid - 1;
        int right = mid + 1;
        while (true){
            if (left < first && right > last){
                return -1;
            }
            else if (right <= last && !strings[right].isEmpty()){
                mid = right;
                break;
            }
            else if (left >= first && !strings[left].isEmpty()){
                mid = left;
                break;
            }
            right++;
            left--;
        }
    }

    if (str.equals(strings[mid])){ // Found it!
        return mid;
    }
    else if (strings[mid].compareTo(str) < 0){ // Search right
        return search(strings, str, mid + 1, last);
    }
    else {
        return search(strings, str, first, mid - 1);
    }
}
```

