Searcher.java

jmud-0.11/src/util/nice/Searcher.java · 1.5 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

package util.nice;

import java.util.NoSuchElementException;

public class Searcher {

  // encontra a primeira ocorrência
  public static Niceable linearSearch(NiceEnumerable s, NiceKey key) 
    throws NoSuchElementException {
      return linearSearch(s, key, 1);
  }

  // encontra a ind-ésima ocorrência
  public static Niceable linearSearch(NiceEnumerable s, NiceKey key, int ind) 
    throws NoSuchElementException {
    for (NiceEnumeration enum = s.elements(); enum.hasMoreElements(); ) {
      Niceable curr = enum.nextElement();
      if (curr.hasKey(key) && --ind == 0)
	return curr;
    }
    throw new NoSuchElementException();
  }

  // encontra todas as ocorrências
  public static NiceQueue findAll(NiceEnumerable s, NiceKey key) {
    NiceQueue result = new NiceQueue();
    for (NiceEnumeration enum = s.elements(); enum.hasMoreElements(); ) {
      Niceable curr = enum.nextElement();
      if (curr.hasKey(key))
	result.insert(curr);
    }
    return result;
  }

  public static int binarySearch(QuickSortable v, NiceKey key, int first, int last) 
    throws NoSuchElementException {
    Niceable result = null;
    while (first <= last) {
      int mid = (first + last) >> 1;
      Niceable curr = v.getElementAt(mid);
      if (curr.hasKey(key))
	return mid;
      else if (curr.keyLessThan(key))
	first = mid + 1;
      else
	last = mid - 1;
    }
    throw new NoSuchElementException();
  }

  public static int binarySearch(QuickSortable v, NiceKey key) 
    throws NoSuchElementException {
    return binarySearch(v, key, 0, v.getSize() - 1);
  }
}


Site Stats

Snippets: 1791
Codebases: 571