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.. - 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");
-
}
-
}
5 3116
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
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
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).
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? - 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);
-
}
-
-
}
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
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Kakarot |
last post by:
I'm gona be very honest here, I suck at programming, *especially* at
C++. It's funny because I actually like the idea of programming ...
normally what I like I'm atleast decent at. But C++ is a...
|
by: yee young han |
last post by:
I need a fast data structure and algorithm like below condition.
(1) this data structure contain only 10,000 data entry.
(2) data structure's one entry is like below
typedef struct _DataEntry_...
|
by: Aravind |
last post by:
Hi folks.
I have a form, frmHistory, which has 4 command buttons: Sort Title
(cmdSortTitle), Sort Name (cmdSortName), Due Today (cmdDueToday), and
Due List (cmdDueList).
Sort Title and Sort...
|
by: David Garamond |
last post by:
in oracle 10g, you can issue:
ALTER SESSION SET NLS_COMP = ansi;
ALTER SESSION SET NLS_SORT = binary_ci;
do you think this is an elegant solution for case insensitive sorting &
searching? is...
|
by: nubleo |
last post by:
I need a help using a sorting and searching function ,Bimary search or selection sort.. ASAP..
Your help greatly appreciate. :) This is my first time posting ..
|
by: Kuku |
last post by:
Hi,
Can anyone please tell me good books/sites for sorting and searching.
Finding it a little hard to understand
|
by: Karl |
last post by:
I have a continous form based on 1 table.
On the form I have a button that sets the OrderBy to as follows
DataSource = Me.RecordSource
If Me.OrderBy = DataSource & ".PaymentDate DESC" Then...
|
by: Corster |
last post by:
I went through a great deal of hassle to figure this out for myself, but now it is complete, I would like to share it with the world!
I know afew other people have had trouble with FindFirst and...
|
by: rupalirane07 |
last post by:
Both grids displays fine. But the problem is only parent datagrid sorting works fine but when i clik on child datagrid for sorting it gives me error:
NullReferenceException error
Any...
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: Aliciasmith |
last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: giovanniandrean |
last post by:
The energy model is structured as follows and uses excel sheets to give input data:
1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
|
by: isladogs |
last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, Mike...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
| |