Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> проблема с последовательным поиском 
:(
    Опции темы
ArniLand
Дата 16.11.2010, 21:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 227
Регистрация: 17.8.2008

Репутация: нет
Всего: нет



При поиске значений в 3 массиве, для примера задаю размерность массива 100, поиск значения задаю 4, при результате выдает 2. Не могу понять в чем ошибка. Значения генерируются генератором случайных чисел. Вот код программы и результат выполнения. package laba5 ;
Код

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.*;
import java.util.*;
/**
 *
 * @author Anton
 */
public class Main {


    public static void main(String[] args) {

        System.out.println("Enter array size: ");
        Scanner in = new Scanner(System.in);
        int M = in.nextInt();
         System.out.println("Enter value to search");
         int p = in.nextInt();

           int[] a = new int[M];

        Random r = new Random(100);

        for (int i = 0; i < M; i++)
            a[i] =  r.nextInt(100);

        Arrays.sort(a); 

linearSearch(a,p); 
int z= a.length;
 long begin = System.nanoTime();
binarySearch(a,p, 0, z);
if(binarySearch(a,p, 0, z) != -1)
{
    System.out.println("\n matches found by binary searching");
}
else System.out.println("\n no matches found");
long v = (System.nanoTime()- begin);
System.out.println("\n Elapsed time is "+v+" nanoseconds");
System.out.println("Enter second value");
p=in.nextInt();
int[] b = new int[p];
 for (int i = 0; i < p; i++)
            b[i] =  r.nextInt(100);
System.out.println("Enter value to search");
         int t = in.nextInt();

        Arrays.sort(b); 
linearSearch(b,t); 
int x= b.length;
 long egin = System.nanoTime();
binarySearch(b,t, 0, x);
if(binarySearch(b,t, 0, x) != -1)
{
    System.out.println("\n matches found by binary searching");
}
else System.out.println("\n no matches found");
long m = (System.nanoTime()- egin);
System.out.println("\n Elapsed time is "+m+" nanoseconds");
System.out.println("Enter the value of array 3");

p=in.nextInt();
int[] c = new int[p];
 for (int i = 0; i < p; i++)
            c[i] =  r.nextInt(100);
System.out.println("Enter value to search");
         int k = in.nextInt();

        Arrays.sort(b);
linearSearch(b,t); 
int y= c.length;
 long begin3 = System.nanoTime();
binarySearch(b,k, 0, y);
if(binarySearch(b,k, 0, y) != -1)
{
    System.out.println("\n matches found by binary searching");
}
else System.out.println("\n no matches found");
long l = (System.nanoTime()- begin3);
System.out.println("\n Elapsed time is "+l+" nanoseconds");


    }


   public static int binarySearch(int[] array, int value, int left, int right) {

      if (left > right)

            return -1;

      int middle = (left + right) / 2;

      if (array[middle] == value) {

            return middle;


      }


      else if (array[middle] > value)

            return binarySearch(array, value, left, middle - 1);

      else

            return binarySearch(array, value, middle + 1, right);

}
    public static void linearSearch(int array1[],  int key) {

        long begin = System.nanoTime();
        int q=0;
        for (int i = 0; i < array1.length; i++) {
        if (key == array1[i]) {
           System.out.println("\n value "+key+" founded at"+ i + "position by by linear searching");
           q++;

        }

    }
             if (q==0)
            System.out.println("\n No matches founded");
          long p = (System.nanoTime()- begin);
            System.out.println("\n Elapsed time is "+p+" nanoseconds");

    }

}


Результат программы:
run:
Enter array size: 
1000
Enter value to search
3

 value 3 founded at34position by by linear searching

 value 3 founded at35position by by linear searching

 value 3 founded at36position by by linear searching

 value 3 founded at37position by by linear searching

 value 3 founded at38position by by linear searching

 value 3 founded at39position by by linear searching

 value 3 founded at40position by by linear searching

 value 3 founded at41position by by linear searching

 Elapsed time is 1149901 nanoseconds

 matches found by binary searching

 Elapsed time is 76990 nanoseconds
Enter second value
75
Enter value to search
2

 value 2 founded at1position by by linear searching

 value 2 founded at2position by by linear searching

 value 2 founded at3position by by linear searching

 Elapsed time is 337106 nanoseconds

 matches found by binary searching

 Elapsed time is 63792 nanoseconds
Enter the value of array 3
100
Enter value to search
4

 value 2 founded at1position by by linear searching

 value 2 founded at2position by by linear searching

 value 2 founded at3position by by linear searching

 Elapsed time is 424545 nanoseconds

 matches found by binary searching

 Elapsed time is 63792 nanoseconds
BUILD SUCCESSFUL (total time: 29 seconds)
PM MAIL   Вверх
_Y_
Дата 16.11.2010, 23:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1651
Регистрация: 27.11.2006

Репутация: 5
Всего: 34



Встроке 70 ввод производится в переменную k, а строка 73 передает методу поиска величину t


--------------------
Я вот в этом поучаствовал: http://sbor-nik.appspot.com/kick.jsp?id=sbor5737960678883328 (на правах саморекламы:)
PM MAIL WWW   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0882 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.