Search Algorithms help

Hi, im a new to java, so dont know much. Can anypne help me with wrtting a basic prog to preform a Sequential Search or Binary Search, with the output to be entered by the user eiter using JPane or command line.
thanks.

Hi there,
For the Sequential search you need just a for loop.
e.g. for a String array
public class serc
  public static void main(String[] args)
    String[] A={"hi","there","how","are","you"};
    String search="how";  //We are searching "how"
    for(int i=0;i<A.length;i++)
      if (A.equals(search))
System.out.println(A[i]);
break;
For the binary sarch try this. Modify it according to your needs.
public class serc
  public static void main(String[] args)
    int[] A=new int[]{1,2,3,4,5,6}; //The array has to be sorted
    int search=5;  //We are searching "5"
    int found=ser.search(A,search,0,A.length);
    System.out.println(found);   //if found it will be printed it's position
   found=ser.search(A,3,0,A.length);
    System.out.println(found);   //if found it will be printed it's position
class ser
  public static int search(int[] a,int s,int start,int end)
    int m=(int)((start+end)/2);
    if (a[m]==s)
      return m;
    else if(a[m]>s)
      return ser.search(a,s,0,m);
    else
      return ser.search(a,s,m,end);
}If you need explanation, just ask for it.
Hope this helped

Similar Messages

  • Creating A Binary search algorithm !!!! URGENT HELP

    hi ..
    i;m currently tryin to create a binary search algorithm ..
    the user should be able to input the size of the array
    and also the key that he would like to find.
    it also has to have to ability to measure the run time of the algorithm.. it how long it too the algorithm to search through the array and find they key..
    i have created 3 classes
    the first class is the binary search class
    which is the mathamatical side of things
    the second class is the Array
    this creates an array selection a random first number
    and then incrementing from there, so that its a sorted array
    the third class is the binary search class
    which is my main class.
    this class should take the users input
    and pass it to the array
    and the binary seach accordingly
    it should also measure the running time, from when it passes the array
    to the binary search class
    i am having a really hard time creating this last class.
    i have created the other 2 successfully
    the codes for the binary search class is as follows
    public class BinarySearch
         static int binSearch(int[] array, int val)
             // setting the start and the end of the array
              int low = 0, high = array.length;
              //While loop
              while(low <= high) {
              // How to find the mid point      
                  int mid = (low + high)/2;
                   // if the mid point is the value return the value
                  if(array[mid] == val) {
                        return mid;
                   // if the value is smaller than the mid point
                   // go search the left half
                   } else if(array[mid] > val) {
                        high = mid - 1;
                   //if the value is greater then the mid point
                   // go search the right half
                   } else if(array[mid] < val) {
                        low = mid + 1;
              // if value is not found return nothing
              return -1;
    }and the code for the Array class is as follows
    import java.util.Random;
    public class RandomSortedArray
        public int[] createArray(int length)
            // construct array of given length
            int[] ary = new int[length];
            // create random number generator
            Random r = new Random();
            // current element of the array; used in the loop below.  Starts at
            // -1 so that the first element of the array CAN be a 0
            int val = -1;
           for( int i = 0; i < length; i++)
                val += 1 + r.nextInt(10);
                ary[i] = val;
            return ary;
    }can some pne please help me create my binarysearchTest class.
    as i mentioned before
    it has to take the users input for the array size
    and the users input for the value that they want to find
    also needs to measure the running time
    thanks for all ur help in advance

    import java.util.*;
    public class AlgorithmTest
         public static void main(String args[])
             long StartTime, EndTime, ElapsedTime;
             System.out.println ("Testing algorithm");
             // Save the time before the algorithm run
             StartTime = System.nanoTime();
             // Run the algorithm
             SelectionSortTest1();
             // Save the time after the run
             EndTime = System.nanoTime();
             // Calculate the difference
             ElapsedTime = EndTime- StartTime;
             // Print it out
             System.out.println("The algorithm took " + ElapsedTime + "nanoseconds to run.");
        }this is the code i managed to work up for measuring the time..
    how would i include it into the main BinarysearchTest Class

  • Java library for local search algorithms?

    Hi everybody,
    Could anyone please help me with the following?
    I am looking for a Java library with already implemented local search algorithms. Does such a thing exist? Would anyone recommend one?
    I am testing several AI programs and need to select the best parameters for each one (in a relatively large number of experiments). I could write my own search algorithm, of course, but it would be so much easier to use several already implemented algorithms and choose the best one.
    Thanks in advance for any pointers.
    Anna

    Here is an interesting question. Say you build the central control system of a rocket ship using Java, should you then be able to ask questions about rocket ships in Java forums?
    Well you can try, but I wouldn't hold your breath to find another rocket scientist in such a place. You may want to go to a forum where rocket scientists congregate in stead. Just a friendly tip.

  • Database Searching Algorithms

    Hi..
    I have to do some research about database searching algorithms.
    Would someone here help me and give a list of that algorithms and which one is the best.
    What is the name of this algorithms which when u type in a key such "a" then it display a list of information that started with "a".

    I guess I have more time than I thought... :)
    Here is a full working example all in one class...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MAIN
         DefaultListModel model_my_list = new DefaultListModel();
        JList my_list = new JList(model_my_list);
         DefaultListModel model_list_of_finds = new DefaultListModel();
        JList list_of_finds = new JList(model_list_of_finds);
         JTextField search_box = new JTextField(20);
         JTextField add_box = new JTextField(20);
         public MAIN()
              JFrame frame = new JFrame( "Search test" );          
              frame.setSize( 500, 500 );
              Container container = frame.getContentPane();
             GridBagLayout gbl = new GridBagLayout();             
             container.setLayout(gbl);
             GridBagConstraints gbc = new GridBagConstraints();
             Action actionAdd = new AbstractAction("ADD")
                 public void actionPerformed(ActionEvent evt)
                      model_my_list.add( model_my_list.size(), add_box.getText() );
                      add_box.setText("");
             JButton buttonAdd = new JButton(actionAdd);
             buttonAdd.setPreferredSize( new Dimension( 100, 30 ) );
             gbc.gridx = 2;
             gbc.gridy = 2;
             gbl.setConstraints(buttonAdd, gbc);
             container.add( buttonAdd );
             Action actionSearch = new AbstractAction("SEARCH")
                 public void actionPerformed(ActionEvent evt)
                      search( search_box.getText() );
             JButton buttonSearch = new JButton(actionSearch);
             buttonSearch.setPreferredSize( new Dimension( 100, 30 ) );
             gbc.gridx = 2;
             gbc.gridy = 4;
             gbl.setConstraints(buttonSearch, gbc);
             container.add( buttonSearch );         
             JLabel add_label = new JLabel( "Add element" );
             gbc.gridx = 1;
             gbc.gridy = 1;
             gbl.setConstraints(add_label, gbc);
             container.add( add_label );
              gbc.gridx = 1;
             gbc.gridy = 2;
             gbl.setConstraints(add_box, gbc);
             container.add( add_box );
             JLabel search_label = new JLabel( "Search keyword" );
             gbc.gridx = 1;
             gbc.gridy = 3;
             gbl.setConstraints(search_label, gbc);
             container.add( search_label );
              gbc.gridx = 1;
             gbc.gridy = 4;
             gbl.setConstraints(search_box, gbc);
             container.add( search_box );
              JLabel all_label = new JLabel( "All elements" );
             gbc.gridx = 1;
             gbc.gridy = 5;
             gbl.setConstraints(all_label, gbc);
             container.add( all_label );
             JScrollPane all_scroll = new JScrollPane( my_list );
              gbc.gridx = 1;
             gbc.gridy = 6;
             gbl.setConstraints(all_scroll, gbc);
             container.add( all_scroll );
              JLabel found_label = new JLabel( "Searched elements" );
             gbc.gridx = 2;
             gbc.gridy = 5;
             gbl.setConstraints(found_label, gbc);
             container.add( found_label );
             JScrollPane found_scroll = new JScrollPane( list_of_finds );
              gbc.gridx = 2;
             gbc.gridy = 6;
             gbl.setConstraints(found_scroll, gbc);
             container.add( found_scroll );
              frame.pack();
              frame.setResizable( false );
              frame.setVisible( true );          
         public void search( String searchWord )
              model_list_of_finds.clear(); //empty
              for ( int i = 0; i < model_my_list.size(); i++ )
                   String text = (String)model_my_list.get(i);
                   if ( text.startsWith( searchWord ) )
                        model_list_of_finds.add( model_list_of_finds.size(), text );
                        continue;
                   if ( text.endsWith( searchWord ) )
                        model_list_of_finds.add( model_list_of_finds.size(), text );
                        continue;
                   String keyword[]  = text.split( searchWord );
                   if (keyword.length > 1 ) //if there was a split... there was a find
                     model_list_of_finds.add( model_list_of_finds.size(), text );
                     continue;
         public static void main ( String args[] )
              new MAIN();
    }

  • I normally dont need a login when I install new program, but I try to Install a new flash player im asked to write a login and I have no clue? when I search for help it suggest to put in the original installation cd but that doesnt work. Please help!

    When Trying to install the newest Flash player, Im asked to fill in my login.
    I have no clue what my login is. (It happened very rarely that I was asked to fill in this when installing a new program, and the login I have used before are not valid now.
    When I search for help, I am suggested to put in the original installation Cd.. and press the "C" button when I hear the starting sound... but when I do this nothing is happening.
    Please Help me If you have an idea for a solution to this problem!
    / Joel

    You need the admin password you created when you first set up the machine.  Just about every installer running under OS X will require you to authorize the installation by entering an administrator password - even software update requires this.  You really should not forget your admin password, as it is required for many things in OS X since, unlike Windows, you often need to manually type in the admin password to proceed with an install or update (whereas Windows will take admin authority, if you are logged in as an admin, by simply clicking continue or yes).
    If you cannot remember your admin password, you can reset it from the recovery CD that came with your mac - http://support.apple.com/kb/HT1274

  • When I use Firefox for Yahoo mail the tabs such as sign out, search email, help seem to be disabled. How do I make them work? Works in Internet Explorer

    There are a number of tabs at top of my inbox such as sign out, search email, help, etc. They do not work. For example cannot insert a name for search email- will not give me the curser to do this. When I use internet explorer these tabs do work so not a problem with Yahoo mail- must be problem with Firefox. Recently updated Firefox.

    SafeBrowser posted Recently, the Yahoo Toolbar and the Babylon extension have been reported to cause that problem. They seem to overlap invisibly over the top of the web page display. If you have either or both, uninstall or disable them/it, or see if an update is available that solves the problem.
    See --> http://support.mozilla.com/en-US/kb/Uninstalling+add-ons
    I disabled the Babylon extension and Yahoo Mail works now.
    Thank you SafeBrowser

  • Search Algorithm in Java

    Hey Guys,
    I have written a crude search algorithm which extracts 4 fields from a database table into the String type of Java. Then this String object is tokenized and then within these tokens I search for the text the user has used.
    Once, I faced this problem that one of the String pulled from the DB was so huge that I got the OutOfMemory exception. Simple stating it, the text was so big that my system could not store all that text in one String object.
    I resolved this by adding more heap to java by doing:
    java -Xmx512M MySearchClass
    Now I am afraid that if there is another HUGE text in the DB , I can still run out of memory.
    Do I just need to get MORE RAM to my system and allot really huge heap space, such as 4 GB or so , so that if need be, the JVM can use it ?
    Suppose I get a server machine with 4 GB RAM, at some stage I'd still have an upper limit on the amount of text I can extract from the DB, right ?
    Is there any other way to stream the text from DB and then search ? Remember that I am tokenizing the text in the algorithm, so I think I can't use a buffer, or can I ?
    thanks a ton !
    -AZ

    These are SQL queries. I use SQL queries to pull out the text in the DB and then store it in a String object. The problem is that the text in DB can get so huge that the String object cannot hold it anymore due to memory limits. The JVM gets assigned a heap size and the size of the String object can get really big to exceed the heap size.
    I used : java -Xmx512M MySearchClass
    That assigned 512MB to the JVM so I haven't encountered the OutOfMemory exception so far. But my guess is that for some other data set, the String can be so big that even 512MB might not be enough.
    This search algorithm will be deployed on a server class machine with about 4 GB RAM. So we can give JVM 4GB heap space to use. But its a limitation again , right ?
    These text in DB are extracted from PDF files.

  • Please help me. My YouTube app will not work. Every time I open it says 'cannot connect to youtube'. I have searched for help and tried resetting my settings and rebooting my ipad2 but nothing has solved the issue.

    Please help me. My YouTube app will not work. Every time I open it says 'cannot connect to youtube'. I have searched for help and tried resetting my settings and rebooting my ipad2 but nothing has solved the issue.

    Yes, I am connected to the Internet through my wifi. Everything is working fine with the e  eption of youtube.  I have reset all Internet settings and have tried synching to iTunes followed by rebooting.  This is all the advice I have found although none of it has been helpful.
    Has anyone else encountered this problem?

  • Search in Help Viewer always returns "No matching help topics were found".

    Hi!
    I'm running 10.3.9 on 14" iBook G4.
    Recently re-installed OSX from CD after a hard disk replacement. Help viewer was fine on the original / old installation of the same version number of OSX.
    The CD installs a version earlier than 10.3.9. Possibly 10.3.4? Cannot recall... is this important?
    After HDD replacement, went through all the updates fairly rapidly, and arrived at version 10.3.9. Excellent! Except one thing (there may be more, but I've only discovered this so far!)... searches in Help Viewer return the same message irrespective of what I search for. I type the search string (e.g. "dvd" ) in the search bubble in the Viewer window. The message is as follows:
    [bouyancy aid with question mark logo] No matching help topics were found
    I have tried the usual things, without success, of:
    - Removing the Famous Four cache and preference files/dirs.
    - Repairing permissions. This repaired a few 'permissions'.
    - Rebooting.
    I think the icon of the bouyancy aid is a comic irony, but very well suited to my situation. Anyone out there with any suggestions on how to fix, please?
    RSJ

    Excellent pointers, thanks!
    I haven't quite got it working, yet, but have got it to a point that is better than nothing.
    Very peculiar -- discovered that, after trying many of the troubleshooting ideas without success, the solution was to hit the "back" icon on the viewer to get to the list of help topics satisfying my search criteria... cannot work out why. It would appear that, for some reason, the viewer is skipping the page with the help topics, and going directly to the "No topics found" page. Curious. I am wondering if one of the above activities (from your help pages) may have helped.
    Anyway. Thanks very much for your help on this, and your *very* rapid responses.
    Yours most impressed,
    RSJ.

  • Need algorithm help

    I need some help with my 3 class hangman program.
    whenever the program is run, it doesn't function as intended when a letter is entered. Any advice is greatly appreciated.
    Here's what I have so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //<applet code="Hangman.class" width=400 height=400>
    //</applet>
    public class Hangman extends JApplet implements ActionListener
         private final int WIDTH = 400;
         private final int HEIGHT = 400;
         private JPanel panel,tools;
         private JLabel inputLabel;
         private Hang drawing;
         private JTextField guess;
         RandomWord t = new RandomWord();
         public String answer = t.getWord();
         public void init()
              tools = new JPanel();
              tools.setLayout(new BoxLayout(tools,BoxLayout.X_AXIS));
              tools.setBackground(Color.yellow);
              tools.setOpaque(true);
              guess = new JTextField(1);
              guess.addActionListener(this);
              inputLabel = new JLabel("Enter Guess:");
              tools.add(inputLabel);
              tools.add(guess);
              drawing = new Hang();
              panel = new JPanel();
              panel.add(tools);
              panel.add(drawing);
              getContentPane().add(panel);
              setSize(WIDTH,HEIGHT);
         public void actionPerformed(ActionEvent event)
              String g = guess.getText();
              int incorr = 0;
              int c = 0;
              int i;
              for(i = 0;i<answer.length();i++)
                   if((answer.substring(i,i+1)).equals(g))
                        c++;
                        drawing.setLetter(i,g);
              if(c == 0)
                   incorr++;
                   drawing.setIndex(incorr);
              repaint();
    // class number 2:
    import java.awt.*;
    import javax.swing.JPanel;
    public class Hang extends JPanel
         private final int PAN_HEI = 400;
         private final int PAN_WID = 400;
         private int index;
         private int posNum,corr = 0;
         private String print;
         public Hang()
              setBackground(Color.black);
              setPreferredSize(new Dimension(PAN_WID,PAN_HEI));
         public void setIndex(int v)
              index = v;
         public void setLetter(int y,String s)
              print = s;
              posNum = y + 1;
         public void drawBase(Graphics page)
              setBackground(Color.white);
              page.setColor(Color.black);
              page.fillRect(0,350,150,50);// base
              page.fillRect(0,150,25,200);
              page.fillRect(0,125,100,25);
              page.setColor(Color.gray);
              page.fillRect(84,125,7,50);// rope
              page.setColor(Color.black);
              page.drawOval(75,175,24,25);// head
              page.drawLine(250,55,255,55);
              page.drawLine(260,55,265,55);
              page.drawLine(270,55,275,55);
              page.drawLine(280,55,285,55);     
              page.drawLine(290,55,295,55);
              page.drawLine(300,55,305,55);
              page.drawLine(310,55,315,55);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              this.drawBase(page);
              if(index == 1)
                   page.drawLine(84,200,84,250);
              if(index == 2)
                   page.drawLine(84,215,34,175);
              if(index == 3)
                   page.drawLine(84,215,116,175);
              if(index == 4)
                   page.drawLine(84,250,50,300);
              if(index == 5)
                   page.drawLine(84,250,100,300);
                   page.drawString("You Lose",250,75);
              if(posNum == 1)
                   corr++;
                   page.drawString(print,250,50);
              if(posNum == 2)
                   corr++;
                   page.drawString(print,260,50);
              if(posNum == 3)
                   corr++;
                   page.drawString(print,270,50);
              if(posNum == 4)
                   corr++;
                   page.drawString(print,280,50);
              if(posNum == 5)
                   corr++;
                   page.drawString(print,290,50);
              if(posNum == 6)
                   corr++;
                   page.drawString(print,300,50);
              if(posNum == 7)
                   corr++;
                   page.drawString(print,310,50);
              if(corr == 7)
                   page.drawString("You Win",250,75);
    //last class :
    import java.util.Random;
    public class RandomWord
         Random g = new Random();
         String w1;
         String w2;
         String w3;
         String w4;
         String w5;
         String w6;
         String w7;
         String w8;
         public RandomWord()
              w1 = "freedom";
              w2 = "justice";
              w3 = "impulse";
              w4 = "destiny";
              w5 = "celsius";
              w6 = "ignited";
              w7 = "believe";
              w8 = "realize";
         public String getWord()
              String x = " ";
              int a = g.nextInt(6);
              if(a == 0) x = w1;
              if(a == 1) x =  w2;
              if(a == 2) x =  w3;
              if(a == 3) x = w4;
              if(a == 4) x = w5;
              if(a == 5) x = w6;
              if(a == 6) x = w7;
              if(a == 7) x = w8;
              return x;
    }I'm a very inexperiencd programmer as you can see.

    Darn, I thought you actually needed algorithm help. But instead all I see is:
    "Here's all my code. It doesn't work right. Let me plop it onto your virtual desk and ask that you just fix it for me. I'm going shopping (or whatever) and will be back soon."

  • When i type a search term in the URL box, the result is returned on an AOL Search page; I want a Google search page - help....

    When i type a search term in the URL box, the result is returned on an AOL Search page; I want a Google search page - help....

    In order to better assist you with your issue please provide us with a screenshot. If you need help to create a screenshot, please see [[How do I create a screenshot of my problem?]]
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. This will help us to visualize the problem.
    Thank you!

  • Search Algorithms in Oracle

    What are the search algorithms that Oracle supports?

    You use SQL to select from a database. You can find the Oracle SQL syntax documentation on tahiti.oracle.com
    If you want to get down lower and find how the sql syntax is implemented, then some of this is documented on metalink.oracle.com in notes, and some is in books, and some is unknown ... (you could research your whole life ....)
    If you need to ask this question, I think you should start with the basics of blocks, memory, processes, undo, redo etc.

  • Account search F4 Help from BP Relationship page restricts the search

    Hi ,
    Account search F4 Help from BP Relationship page restricts the search to corporate accounts.
    The business partner category maintained for the relationship type in Tcode buba is organization and person.But the search is restricted to corporate accounts only.
    Thanks & Regards,
    Sanila

    Hi Shobhi,
    Can you provide some more details about the system ?
    Are you using transaction BP or CRM Web UI ? Also, which BBPCRM SP are you on ?
    This problem does not exist in higer SPs of CRM, and a related problem existed in Web UI that the F4 search did not consider the role based customizing. This has been corrected in SAP note 1297760.
    My guess is that everything is working fine in your system. Probably, you have also maintained some role based restrictions in BUBA customizing. Now, possibly, the allowed roles are only valid for corporate accounts, that's why you only see organizations in the search.
    E.g : say u have a relationship category ZBUP03 - Employee rel
    Now, you have a role restriction that partner 2 must be only role BUP003 = employee.
    Now, according to role customizing, employee can only be person.
    Thus, when you search for BP's to assign to rel category ZBUP03, you will only see persons.
    Probably, this is the scenario in your system.
    Hope this helps.
    Cheers,
    Rishu.

  • HT201407 i've updated my iphone 3gs software to the latest version of ios and now my device does not activate. i've searched for help here and it still doesn't work...is there anything else i can do, or i have to take the device back to the store?

    i've updated my iphone 3gs software to the latest version of ios and now my device does not activate. i've searched for help here and it still doesn't work...is there anything else i can do, or i have to take the device back to the store?

    Where did you buy this iPhone and how did you unlock it?

  • Search Community Help?

    If I do a search under Search Community Help, no answers appear. Where are they? What is that search used for?
    Thanks,
    Harry

    harry hh wrote:
    If I do a search under Search Community Help, no answers appear. Where are they? What is that search used for?
    Thanks,
    Harry
    You are not the only one to complain about the search facility here.  Adobe Forum Comments forum is full of complaints about this function.  Google is the best "first port of call" for searching anything.

Maybe you are looking for

  • A Petition to ask Creative to update the firmware of the Zen Touch to Include EAX capabiliti

    <SPAN>Hi. I have been looking for a new hard dri've MP3 player and am thinking about getting the Zen Touch. But I was unhappy that creative removed the EAX functions that were in their other players. I will be sending this to creative to show them th

  • Can you hide the "unique tracking number" in the email subject line?

    I noticed that if I use the "New Activity -> Email" function from the CRM toolbar in Outlook, it appends the subject line with a CRM:XXXXXXX unique tracking number.  I'm not sure that my customers would react very well to knowing that I am tracking t

  • Changing Graphics Card Settings

    Hi there I have a 24 inch iMac and when I run Maya (the 3d software) the timeline does not show up at the bottom of the screen. It works fine on my old G4 so what is the problem here? I figure I need to change graphics card options somewhere but have

  • Cant Display charts in browser with CrystalReportViewer

    I am integrating crystal reports with Struts.I could get the reporting data in the browser with crystal report viewer.but i cant dispaly reports that contain charts in the browser.when i am trying to execute,i m getting following exception. com.cryst

  • Extension Manager javascript error 2

    I am getting so many errors with DW8 I am not sure what to do. Everytime I try to open a page, when I try to cut and paste... Oh my! HELP PLEASE! Thanks!