By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,558 Members | 1,607 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,558 IT Pros & Developers. It's quick & easy.

Searching Sorting Exit

P: 3
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..

Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.util.Arrays;
  3. import java.util.Random;
  4. /** Generate 10 random integers in the range 0..99. */
  5. public final class Main {
  6.     public int first,  middle,  last;
  7.     public int[] list;
  8.     public Scanner lim = new Scanner(System.in);
  9.  
  10.     public int binarysearch(int[] list, int searchTarget) {
  11.  
  12.         last = list.length - 1;
  13.         first = 0;
  14.         // while there are still elements to search through
  15.         while (first <= last) {
  16.             middle = (first + last) / 2;
  17.             // if current middle value is the search target
  18.             if (list[middle] == searchTarget) {
  19.                 return middle;
  20.             } // if current middle value is less than the search target
  21.             else if (list[middle] < searchTarget) {
  22.                 first = middle + 1;
  23.             } // if current middle value is larger than the search target
  24.             else {
  25.                 last = middle - 1;
  26.             }
  27.         }
  28.         // return 0 if search target not found
  29.         return 0;
  30.     }
  31.     public int linearSearch(int[] a, int first, int upto, int key) {
  32.  
  33.         for (int i = first; i < upto; i++) {
  34.             if (key == a[i]) {
  35.                 return i;  // Found key, return index.
  36.             }
  37.         }
  38.         return -1;        // Failed to find key
  39.     }
  40.     public void showWhatToDoMenu(int[] arrNum, int y) {
  41.     while(true){
  42.  
  43.             System.out.println("What do you want to perform choose :\n 1. Searching\n 2. Sorting\n 3. Exit\n ");
  44.             Scanner input = new Scanner(System.in);
  45.             int result;
  46.                 switch(input.nextInt()){
  47.                         case 1 : System.out.println("1. Linear Searching\n2. Binary Searching\n");
  48.                                     switch(input.nextInt()){
  49.                                         case 1 : result=linearSearch(arrNum, 0, arrNum.length, y);
  50.                                                     if (result!=-1) System.out.println("I found number "+y+" on index "+result+"."); 
  51.                                                     else System.out.println("Number not found.");
  52.                                         continue;
  53.                                         case 2 : result=binarysearch(arrNum, y);
  54.                                                     if (result!=0) System.out.println("I found number "+y+" on index "+result+"."); 
  55.                                                     else System.out.println("Number not found.");
  56.  
  57.                                         continue;
  58.                                         }
  59.                         //continue;                 //starts the loop again
  60.                         case 2 : System.out.println("1. Bubble Sorting \n2. Selection Sorting\n3. Insertion\n");
  61.                                     switch (input.nextInt()){
  62.                                         case 1 : bublesort();
  63.                                         continue;
  64.                                         case 2 : insertion();
  65.                                         continue;
  66.                                         case 3 : selection();
  67.                                         continue;
  68.                                         }
  69.                         break;                   //calls your sortingmethod
  70.                       //continue;                   //starts the loop again
  71.                         case 3 : System.exit(0);
  72.                         break;                                //exists the loop 
  73.                         default: System.out.println(input.nextInt()+ "is not a valid charachter , please try again");
  74.             }
  75.         }//end of while loop
  76.    }
  77.  
  78.    public void showMainMenu() {
  79.         System.out.println("Please Enter a Search Key: ");
  80.         int y = lim.nextInt();
  81.         int[] arrNum = new int[20];
  82.         Random randomGenerator = new Random();
  83.         for (int idx = 1; idx <= 20; ++idx) {
  84.             int randomInt = randomGenerator.nextInt(100);
  85.             arrNum[idx - 1] = randomInt;
  86.         }
  87.  
  88.         System.out.println(Arrays.toString(arrNum));
  89.         System.out.println("\n");
  90.         showWhatToDoMenu(arrNum, y);
  91.     }
  92.  
  93.  
  94.     public static void main(String[] args) { 
  95.         new Main().showMainMenu();
  96.     }
  97.  
  98.  
  99.     public static void binarysearch() {
  100.         throw new UnsupportedOperationException("Not yet implemented");
  101.     }
  102.  
  103.     private static void bublesort() {
  104.         throw new UnsupportedOperationException("Not yet implemented");
  105.     }
  106.  
  107.     private static void insertion() {
  108.         throw new UnsupportedOperationException("Not yet implemented");
  109.     }
  110.  
  111.  
  112.  
  113.  
  114.     private static void selection() {
  115.         throw new UnsupportedOperationException("Not yet implemented");
  116.     }
  117.    }
Aug 24 '08 #1
Share this Question
Share on Google+
5 Replies


Expert 10K+
P: 11,448
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
Aug 24 '08 #2

P: 3
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
Aug 24 '08 #3

Expert 10K+
P: 11,448
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).
Aug 24 '08 #4

P: 3
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 ShowWhatToDoMenu first before show menu in my main class?
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. /** Generate 10 random integers in the range 0..99. */
  3. public final class Main {
  4.     public int first,  middle,  last;
  5.     public int[] list;
  6.     public Scanner lim = new Scanner(System.in);
  7.  
  8.     public int binarySearch(int[] list, int searchTarget) {
  9.  
  10.         last = list.length - 1;
  11.         first = 0;
  12.         // while there are still elements to search through
  13.         while (first <= last) {
  14.             middle = (first + last) / 2;
  15.             // if current middle value is the search target
  16.             if (list[middle] == searchTarget) {
  17.                 return middle;
  18.             } // if current middle value is less than the search target
  19.             else if (list[middle] < searchTarget) {
  20.                 first = middle + 1;
  21.             } // if current middle value is larger than the search target
  22.             else {
  23.                 last = middle - 1;
  24.             }
  25.         }
  26.         // return 0 if search target not found
  27.         return 0;
  28.     }
  29.     public int linearSearch(int[] a, int first, int upto, int key) {
  30.  
  31.         for (int i = first; i < upto; i++) {
  32.             if (key == a[i]) {
  33.                 return i;  // Found key, return index.
  34.             }
  35.         }
  36.         return -1;        // Failed to find key
  37.     }
  38.  
  39.     private static void bubbleSort(int[] x) {
  40.     int n = x.length;
  41.     boolean doMore = true;
  42.     while (doMore) {
  43.         n--;
  44.         doMore = false;
  45.         for (int i=0; i<n; i++) {
  46.             if (x[i] > x[i+1]) {
  47.  
  48.                 int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;
  49.                 doMore = true;
  50.             }
  51.         }
  52.     }
  53. }
  54.  
  55.   public static void selectionSort(int[] x) {
  56.     for (int i=0; i<x.length-1; i++) {
  57.         int minIndex = i;
  58.         for (int j=i+1; j<x.length; j++) {
  59.             if (x[minIndex] > x[j]) {
  60.                 minIndex = j;
  61.             }
  62.         }
  63.         if (minIndex != i) { 
  64.             int temp = x[i];
  65.             x[i] = x[minIndex];
  66.             x[minIndex] = temp;
  67.         }
  68.     }
  69. }
  70.   public static void insertionSort( Comparable [ ] a )
  71.     {
  72.         for( int p = 1; p < a.length; p++ )
  73.         {
  74.             Comparable tmp = a[ p ];
  75.             int j = p;
  76.  
  77.             for( ; j > 0 && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
  78.                 a[ j ] = a[ j - 1 ];
  79.             a[ j ] = tmp;
  80.         }
  81.     }
  82.  
  83.     public void showWhatToDoMenu(int[] arrNum, int y) {
  84.     while(true){
  85.  
  86.             System.out.println("What do you want to perform choose :\n 1. Searching\n 2. Sorting\n 3. Exit\n ");
  87.             Scanner input = new Scanner(System.in);
  88.             int result;
  89.                 switch(input.nextInt()){
  90.                         case 1 : System.out.println("1. Linear Searching\n2. Binary Searching\n");
  91.                                     switch(input.nextInt()){
  92.                                         case 1 : //new Main().showMainMenu();
  93.                                             result=linearSearch(arrNum, 0, arrNum.length, y);
  94.                                                     if (result!=-1) System.out.println("I found number "+y+" on index "+result+"."); 
  95.                                                     else System.out.println("Number not found.");
  96.                                         continue;
  97.                                         case 2 : result=binarySearch(arrNum, y);
  98.                                                     if (result!=0) System.out.println("I found number "+y+" on index "+result+"."); 
  99.                                                     else System.out.println("Number not found.");
  100.  
  101.                                         continue;
  102.                                         }
  103.                         //continue;                 //starts the loop again
  104.                         case 2 : System.out.println("1. Bubble Sorting \n2. Selection Sorting\n3. Insertion\n");
  105.                                     switch (input.nextInt()){
  106.                                        // case 1 : bubleSort();
  107.                                        // continue;
  108.                                        // case 2 : insertionSort();
  109.                                         //continue;
  110.                                         //case 3 : selectionSort();
  111.                                         //continue;
  112.                                         }
  113.                         continue;                   //calls your sortingmethod
  114.                       //continue;                   //starts the loop again
  115.                         case 3 : System.exit(0);
  116.                         break;                                //exists the loop 
  117.                         default: System.out.println(input.nextInt()+ "is not a valid charachter , please try again");
  118.             }
  119.         }//end of while loop
  120.    }
  121.  
  122.    public void showMainMenu() {
  123.         System.out.println("Please Enter a Search Key: ");
  124.         int y = lim.nextInt();
  125.         int[] arrNum = new int[20];
  126.         Random randomGenerator = new Random();
  127.         for (int idx = 1; idx <= 20; ++idx) {
  128.             int randomInt = randomGenerator.nextInt(100);
  129.             arrNum[idx - 1] = randomInt;
  130.         }
  131.  
  132.         System.out.println(Arrays.toString(arrNum));
  133.         System.out.println("\n");
  134.         showWhatToDoMenu(arrNum, y);
  135.     }
  136.  
  137.     public static void main(String[] args) { 
  138.         //new Main().showMainMenu();
  139.         new Main().showWhatToDoMenu(arrNum, y);
  140.     }
  141.  
  142.    }
Aug 24 '08 #5

Expert 10K+
P: 11,448
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 ShowWhatToDoMenu 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
Aug 24 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.