Searching Sorting Exit

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lemlimlee
    New Member
    • Aug 2008
    • 3

    Searching Sorting Exit

    hello,
    this is the task i need to do:

    For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The search algorithms that can be used are Linear Search and Binary Search. The sorting algorithms are bubble, selection and Insertion sort.
    First, the user is asked whether he/she wants to perform a search option, a sort operation, or exit the program. If the user chooses to do searching, the program will create an array consisting of 20 randomly generated integers between 1 and 100. The users then provide a search key between 1 and 100. The program should then display the contents of the array created and inform the user if the search key is in the array or not. If it is in the array, the index where it is located should also be displayed.

    If the user chooses to perform sorting, then he/she will be asked to provide the size of the array that heeds to be sorted. The size should be between 5 and 30. The user is also given an option to choose whether he/she wants to supply the numbers (between 1 and 100) to be sorted or these are to be generated randomly. If these are to be randomly generated then the program should generate the appropriate numbers, store them in an array, and display the contents of the array. Otherwise, the user will be asked to enter or input the numbers one at a time. The program should also store these numbers in an array and display the contents.
    Afterwards, the user is asked to which sorting algorithm he/she wants to use. Upon selection the program then proceeds to perform the sorting algorithm and display both the unsorted and the sorted arrays.
    The program should not exit after performing an operation desired by the user. It should again present the user the option of performing an operation or exit the program. It will only end or exit if the user chooses the exit option.

    im kinda stuck in my code here.. and taking a hard time to solve this my binary search is not working well and i want my menu to first appear 1.Searching 2. Sorting 3. Exit im trying to modify this code to accomplish the task but im taking a hard time keeping on the track Please help me..

    Code:
    import java.util.Scanner;
    import java.util.Arrays;
    import java.util.Random;
    /** Generate 10 random integers in the range 0..99. */
    public final class Main {
        public int first,  middle,  last;
        public int[] list;
        public Scanner lim = new Scanner(System.in);
     
        public int binarysearch(int[] list, int searchTarget) {
     
            last = list.length - 1;
            first = 0;
            // while there are still elements to search through
            while (first <= last) {
                middle = (first + last) / 2;
                // if current middle value is the search target
                if (list[middle] == searchTarget) {
                    return middle;
                } // if current middle value is less than the search target
                else if (list[middle] < searchTarget) {
                    first = middle + 1;
                } // if current middle value is larger than the search target
                else {
                    last = middle - 1;
                }
            }
            // return 0 if search target not found
            return 0;
        }
        public int linearSearch(int[] a, int first, int upto, int key) {
     
            for (int i = first; i < upto; i++) {
                if (key == a[i]) {
                    return i;  // Found key, return index.
                }
            }
            return -1;        // Failed to find key
        }
        public void showWhatToDoMenu(int[] arrNum, int y) {
        while(true){
     
                System.out.println("What do you want to perform choose :\n 1. Searching\n 2. Sorting\n 3. Exit\n ");
                Scanner input = new Scanner(System.in);
                int result;
                    switch(input.nextInt()){
                            case 1 : System.out.println("1. Linear Searching\n2. Binary Searching\n");
                                        switch(input.nextInt()){
                                            case 1 : result=linearSearch(arrNum, 0, arrNum.length, y);
                                                        if (result!=-1) System.out.println("I found number "+y+" on index "+result+"."); 
                                                        else System.out.println("Number not found.");
                                            continue;
                                            case 2 : result=binarysearch(arrNum, y);
                                                        if (result!=0) System.out.println("I found number "+y+" on index "+result+"."); 
                                                        else System.out.println("Number not found.");
                            
                                            continue;
                                            }
                            //continue;                 //starts the loop again
                            case 2 : System.out.println("1. Bubble Sorting \n2. Selection Sorting\n3. Insertion\n");
                                        switch (input.nextInt()){
                                            case 1 : bublesort();
                                            continue;
                                            case 2 : insertion();
                                            continue;
                                            case 3 : selection();
                                            continue;
                                            }
                            break;                   //calls your sortingmethod
                          //continue;                   //starts the loop again
                            case 3 : System.exit(0);
                            break;                                //exists the loop 
                            default: System.out.println(input.nextInt()+ "is not a valid charachter , please try again");
                }
            }//end of while loop
       }
        
       public void showMainMenu() {
            System.out.println("Please Enter a Search Key: ");
            int y = lim.nextInt();
            int[] arrNum = new int[20];
            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 20; ++idx) {
                int randomInt = randomGenerator.nextInt(100);
                arrNum[idx - 1] = randomInt;
            }
     
            System.out.println(Arrays.toString(arrNum));
            System.out.println("\n");
            showWhatToDoMenu(arrNum, y);
        }
        
      
        public static void main(String[] args) { 
            new Main().showMainMenu();
        }
    
       
        public static void binarysearch() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        private static void bublesort() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        private static void insertion() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
       
       
    
        private static void selection() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
       }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Of course your binary search doesn't work if your array isn't sorted. btw, why do
    you have two binary search methods?

    kind regards,

    Jos

    Comment

    • lemlimlee
      New Member
      • Aug 2008
      • 3

      #3
      Originally posted by JosAH
      Of course your binary search doesn't work if your array isn't sorted. btw, why do
      you have two binary search methods?

      kind regards,

      Jos
      oh sorry i forgot to erase the the other method placed in the lower part of the code. oh i need to sort the array first before i perform binary search? im new to this technology im doing this code for almost 3 days but thats the only code i accomplish.. please help

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by lemlimlee
        oh sorry i forgot to erase the the other method placed in the lower part of the code. oh i need to sort the array first before i perform binary search? im new to this technology im doing this code for almost 3 days but thats the only code i accomplish.. please help
        Yep, binary search only works when the array is sorted; read the relevant sections
        in your text books before you attempt to code an algorithm you don't understand.
        There are complete implementations of that (simple) algorithm on the net as well.

        kind regards,

        Jos

        ps. there are also a few short articles available on sorting in Java's 'Howtos' section.
        (see the blue menu bar near the top of this page).

        Comment

        • lemlimlee
          New Member
          • Aug 2008
          • 3

          #5
          Originally posted by JosAH
          Yep, binary search only works when the array is sorted; read the relevant sections
          in your text books before you attempt to code an algorithm you don't understand.
          There are complete implementations of that (simple) algorithm on the net as well.

          kind regards,

          Jos

          ps. there are also a few short articles available on sorting in Java's 'Howtos' section.
          (see the blue menu bar near the top of this page).
          Thanks!

          may you please help me to modify little of my code i dont mean to do it all but at lease help me to call ShowWhatToDoMen u first before show menu in my main class?
          Code:
          import java.util.*;
          /** Generate 10 random integers in the range 0..99. */
          public final class Main {
              public int first,  middle,  last;
              public int[] list;
              public Scanner lim = new Scanner(System.in);
           
              public int binarySearch(int[] list, int searchTarget) {
           
                  last = list.length - 1;
                  first = 0;
                  // while there are still elements to search through
                  while (first <= last) {
                      middle = (first + last) / 2;
                      // if current middle value is the search target
                      if (list[middle] == searchTarget) {
                          return middle;
                      } // if current middle value is less than the search target
                      else if (list[middle] < searchTarget) {
                          first = middle + 1;
                      } // if current middle value is larger than the search target
                      else {
                          last = middle - 1;
                      }
                  }
                  // return 0 if search target not found
                  return 0;
              }
              public int linearSearch(int[] a, int first, int upto, int key) {
           
                  for (int i = first; i < upto; i++) {
                      if (key == a[i]) {
                          return i;  // Found key, return index.
                      }
                  }
                  return -1;        // Failed to find key
              }
              
              private static void bubbleSort(int[] x) {
              int n = x.length;
              boolean doMore = true;
              while (doMore) {
                  n--;
                  doMore = false;
                  for (int i=0; i<n; i++) {
                      if (x[i] > x[i+1]) {
                       
                          int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;
                          doMore = true;
                      }
                  }
              }
          }
              
            public static void selectionSort(int[] x) {
              for (int i=0; i<x.length-1; i++) {
                  int minIndex = i;
                  for (int j=i+1; j<x.length; j++) {
                      if (x[minIndex] > x[j]) {
                          minIndex = j;
                      }
                  }
                  if (minIndex != i) { 
                      int temp = x[i];
                      x[i] = x[minIndex];
                      x[minIndex] = temp;
                  }
              }
          }
            public static void insertionSort( Comparable [ ] a )
              {
                  for( int p = 1; p < a.length; p++ )
                  {
                      Comparable tmp = a[ p ];
                      int j = p;
          
                      for( ; j > 0 && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
                          a[ j ] = a[ j - 1 ];
                      a[ j ] = tmp;
                  }
              }
              
              public void showWhatToDoMenu(int[] arrNum, int y) {
              while(true){
           
                      System.out.println("What do you want to perform choose :\n 1. Searching\n 2. Sorting\n 3. Exit\n ");
                      Scanner input = new Scanner(System.in);
                      int result;
                          switch(input.nextInt()){
                                  case 1 : System.out.println("1. Linear Searching\n2. Binary Searching\n");
                                              switch(input.nextInt()){
                                                  case 1 : //new Main().showMainMenu();
                                                      result=linearSearch(arrNum, 0, arrNum.length, y);
                                                              if (result!=-1) System.out.println("I found number "+y+" on index "+result+"."); 
                                                              else System.out.println("Number not found.");
                                                  continue;
                                                  case 2 : result=binarySearch(arrNum, y);
                                                              if (result!=0) System.out.println("I found number "+y+" on index "+result+"."); 
                                                              else System.out.println("Number not found.");
                                  
                                                  continue;
                                                  }
                                  //continue;                 //starts the loop again
                                  case 2 : System.out.println("1. Bubble Sorting \n2. Selection Sorting\n3. Insertion\n");
                                              switch (input.nextInt()){
                                                 // case 1 : bubleSort();
                                                 // continue;
                                                 // case 2 : insertionSort();
                                                  //continue;
                                                  //case 3 : selectionSort();
                                                  //continue;
                                                  }
                                  continue;                   //calls your sortingmethod
                                //continue;                   //starts the loop again
                                  case 3 : System.exit(0);
                                  break;                                //exists the loop 
                                  default: System.out.println(input.nextInt()+ "is not a valid charachter , please try again");
                      }
                  }//end of while loop
             }
              
             public void showMainMenu() {
                  System.out.println("Please Enter a Search Key: ");
                  int y = lim.nextInt();
                  int[] arrNum = new int[20];
                  Random randomGenerator = new Random();
                  for (int idx = 1; idx <= 20; ++idx) {
                      int randomInt = randomGenerator.nextInt(100);
                      arrNum[idx - 1] = randomInt;
                  }
           
                  System.out.println(Arrays.toString(arrNum));
                  System.out.println("\n");
                  showWhatToDoMenu(arrNum, y);
              }
             
              public static void main(String[] args) { 
                  //new Main().showMainMenu();
                  new Main().showWhatToDoMenu(arrNum, y);
              }
            
             }

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by lemlimlee
            may you please help me to modify little of my code i dont mean to do it all but at lease help me to call ShowWhatToDoMen u first before show menu in my main class?
            You haven't decomposed the functionality properly, that's why your main menu
            ends up with a hodge podge of functionality: it asks for a search key, it creates
            an array and call the other menu. It shouldn't do that all, it is not a Swiss Army
            knife.

            Better make your arrNum array a member of that class: it either exists already
            or it doesn't. If it doesn't exist print a menu option that allows the user to create
            one. Same thing with that search key: the user already supplied one or she didn't.

            Adjust your menu structure accordingly: if the user wants to search for something,
            that something needs to be supplied by the user already.

            Menu structures can be quite complicated to set up according to the context
            of the entire application but there's no need to worry: simply design the thing
            first and only then start coding.

            btw, why is one of the sorting methods not taking an int array as its parameter?
            Did you find that method somewhere on the net and simply copy/pasted it?

            kind regards,

            Jos

            Comment

            Working...