BEST Binary Search!


SUBMITTED BY: Guest

DATE: May 29, 2014, 4:06 p.m.

FORMAT: Java

SIZE: 2.6 kB

HITS: 2076

  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package ricercabinariascuola;
  7. import java.util.Vector;
  8. import java.io.File;
  9. import java.io.FileNotFoundException;
  10. import java.util.Scanner;
  11. /**
  12. *
  13. * @author Marco
  14. */
  15. public class SpecialVector extends Vector {
  16. public SpecialVector (String csvFileName) {
  17. String tmp;
  18. String[] lista;
  19. Scanner lettore = null;
  20. try {
  21. lettore = new Scanner (new File(csvFileName));
  22. }
  23. catch(FileNotFoundException ex) {
  24. System.out.println("Errore in apertura file: " + ex.toString());
  25. }
  26. while (lettore.hasNextLine()) {
  27. tmp = lettore.nextLine();
  28. lista = tmp.split(";");
  29. this.add(lista[1]);
  30. }
  31. }
  32. int puoEsistere = 0;
  33. public int ricercaBin (String searchedString, int idxStart, int idxStop) {
  34. int mid = (int) ((idxStop + idxStart) / 2);
  35. while (puoEsistere < 2) {
  36. if (mid == idxStop) {
  37. puoEsistere ++;
  38. }
  39. String tmpS = (String) this.elementAt(mid);
  40. int tmp = tmpS.compareToIgnoreCase(searchedString);
  41. if (tmp == 0) {
  42. return mid;
  43. }
  44. else if (tmp > 0) {
  45. return this.ricercaBin(searchedString, idxStart, mid - 1);
  46. }
  47. else {
  48. return this.ricercaBin(searchedString, mid + 1, idxStop);
  49. }
  50. }
  51. return - 1;
  52. }
  53. public String decodifica (int posizione, String csvFileName) {
  54. this.clear();
  55. String tmp;
  56. String[] lista;
  57. Scanner lettore = null;
  58. try {
  59. lettore = new Scanner (new File(csvFileName));
  60. }
  61. catch(FileNotFoundException ex) {
  62. System.out.println("Errore in apertura file: " + ex.toString());
  63. }
  64. while (lettore.hasNextLine()) {
  65. tmp = lettore.nextLine();
  66. lista = tmp.split(";");
  67. this.add(lista[0]);
  68. }
  69. return (String) this.elementAt(posizione);
  70. }
  71. }

comments powered by Disqus