Question

In Java, write your own methods to do the following: LinearSearch BinarySearch SelectionSort MergeSort InsertionSort BubbleSort...

In Java, write your own methods to do the following:

LinearSearch
BinarySearch
SelectionSort
MergeSort
InsertionSort
BubbleSort

On the given array with the following elements ;

Array : 87, 39, 3, 5 ,9 ,7 ,27,1 , 8 ,6 (use this Array as data for all methods except the BinarySearch method).

All your methods will be in a class.

Write a tester program that will call each of the listed methods from the class above using the given Array as data.

For the binary search method, use this Array : 1, 3, 5, 6, 7, 8, 9, 27, 39, 87

For the Linear Search and Binary search, the user will input the search item in the program

The program should say if the search was successful or a failed search, if the search was successful, then the program should return the index of the search item and the item.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Operations.java
import java.util.Scanner;
class Operations
{
   //method to print array of passed argument array
   public void printArray(int[] ar)
   {
       int i = 0;
       int len = ar.length;
       for(i = 0;i<len;i++)
       {
           System.out.print(ar[i]);
           if(i < len - 1)
           {
               System.out.print(" , ");
           }
       }
   }
   public int linearSearch(int[]ar,int val)
   {
       int i;
       int len = ar.length;
       int ind = -1;
       //linearly search for element
       for(i = 0;i<len;i++)
       {
           if(val == ar[i])
           {
               ind = i;
               break;
           }
       }
       return ind;
   }
   public int binarySearch(int[]ar,int val)
   {
       int ind = -1;
       int len = ar.length;
       int left = 0;
       int right = len - 1;
       int middle;
       //check for the value at middle of array
       while(left <= right)
       {
          
           middle = left + (right - left) /2;
           if(ar[middle] == val)
           {
               ind = middle;
               break;
           }
           //if middle element is < val then the value might be second half
           if(ar[middle] < val)
           {
               left = middle + 1;
           }
           //if middle element is > val then the value might be first half
           else
           {
               right = middle - 1;
           }
       }
       return ind;
   }
   public void selectionSort(int[] ar)
   {
       int i,j;
       int min;
       int len = ar.length;
       int temp;
       //selection sort
       for(i = 0; i < len - 1; i++)
       {
           min = i;
           //assume i_th element as minimum element find the min value from i to len
           for( j = i+1; j < len ; j++)
           {
               if(ar[j] < ar[min])
               {
                   min = j;
               }
           }
           //swap with min element
           temp = ar[i];
           ar[i] = ar[min];
           ar[min] = temp;
       }
   }
   public void merge(int ar[],int left,int middle,int right)
   {
       int len1 = middle - left + 1;
       int len2 = right - middle;
       int[] leftArray = new int[len1];
       int[] rightArray = new int[len2];
       int i,j,k;
      
       //copy len1 values to leftArray(temp array
       for(i = 0;i<len1;i++)
       {
           leftArray[i] = ar[left + i];
       }
       //copy len2 values to rightArray(temp array)
       for(i = 0;i<len2;i++)
       {
           rightArray[i] = ar[middle + 1 + i];
       }
       i = 0;
       j = 0;
       k = left;
       //merge sort the two temp arrays
       while( i < len1 && j < len2)
       {
           if(leftArray[i] <= rightArray[j])
           {
               ar[k] = leftArray[i];
               i++;
           }
           else
           {
               ar[k] = rightArray[j];
               j++;
           }
           k++;
       }
       while( i < len1)
       {
           ar[k] = leftArray[i];
           i++;
           k++;
       }
       while( j < len2)
       {
           ar[k] = rightArray[j];
           j++;
           k++;
       }
   }
   public void mergeSort(int[] ar,int left,int right)
   {
       if(left < right)
       {
           int middle = left + (right - left)/2;
           mergeSort(ar,left,middle);
           mergeSort(ar,middle + 1,right);
           merge(ar,left,middle,right);
       }
      
   }
   public void insertionSort(int[] ar)
{
int len = ar.length;
int i;
int key;
int j;
for(i=1;i < len ;i++)
{
key = ar[i];
j = i-1;
while (j>=0 && ar[j] > key)
{
ar[j+1] = ar[j];
j--;
}
ar[j+1] = key;
}
}
public void bubbleSort(int[] ar)
{
       int i,j;
       int len = ar.length;
       int temp;
       for(i = 0; i < len; i++)
       {
           for(j = 0; j < len-i-1; j++)
           {
               if(ar[j] > ar[j+1])
               {
                   temp = ar[j];
                   ar[j] = ar[j+1];
                   ar[j+1] = temp;
               }
              
           }
       }
   }
  
}
//End of Operations.java
//Tester.java
import java.util.Scanner;
public class Tester
{
   public static void main(String[] args)
   {
       int[] linear = {87,39,3,5,9,7,27,1,8,6};
       int[] selection = {87,39,3,5,9,7,27,1,8,6};
       int[] arrayMerge = {87,39,3,5,9,7,27,1,8,6};
       int[] insertion = {87,39,3,5,9,7,27,1,8,6};
       int[] bubble = {87,39,3,5,9,7,27,1,8,6};
       int[] binary = {1,3,5,6,7,8,9,27,39,87};
       Scanner inp = new Scanner(System.in);
       System.out.print("Enter value to search:");
       int val = inp.nextInt();
      
       Operations tester = new Operations();
       System.out.println(" - - - - - - - Linear Search - - - - - - - - ");
       int res = tester.linearSearch(linear,val);
       if(res == -1)
       {
           System.out.println("Value not found in array");
       }
       else
       {
           System.out.println("Value found in array at index: "+res);
       }
      
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
       System.out.println(" - - - - - - - Binary Search - - - - - - - - ");
       res = tester.binarySearch(binary,val);
       if(res == -1)
       {
           System.out.println("Value not found in array");
       }
       else
       {
           System.out.println("Value found in array at index: "+res);
       }
      
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
       System.out.println(" - - - - - - - Selection Sort - - - - - - - - ");
       tester.selectionSort(selection);
       System.out.println(" - - - - - - - After Sorting - - - - - - - - ");
       tester.printArray(selection);
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
       System.out.println(" - - - - - - - Merge Sort - - - - - - - - ");
       tester.mergeSort(arrayMerge ,0, arrayMerge.length-1);
       System.out.println(" - - - - - - - After Sorting - - - - - - - - ");
       tester.printArray(arrayMerge);
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
       System.out.println(" - - - - - - - Insertion Sort - - - - - - - - ");
       tester.insertionSort(insertion);
       System.out.println(" - - - - - - - After Sorting - - - - - - - - ");
       tester.printArray(insertion);
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
       System.out.println(" - - - - - - - Bubble Sort - - - - - - - - ");
       tester.bubbleSort(bubble);

System.out.println(" - - - - - - - After Sorting - - - - - - - - ");
       tester.printArray(bubble);
       System.out.println(" - - - - - - - - - - - - - - - - - - - - - - ");
      
      
   }
}
//end of code
//screenshots of code and output
Tester.java - C HamaRaDesktop ggJan Sort - Gean Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations.jevaMergeSort.java X Tester java iport Java.util.scanner: public class Tester public static void main (String args) Int[] linear= {87,39,3,5,9, 7, 27,1,8,6); int[l selection-(87,39,3,5,9,7,27,1,8,6 int arrayMerge87,39,3,5,9,7,27,1,8,6 intti insertion87,39, 3, 5, 9,7,27,1,B, 6 inti bubble87,39,3,5,9,7,27,1,B,6 int[] binary-(1,3,S,6,7,8,9,27,39,87 Scanner inpne Scanner (System.in): System.out print (Enter value to search:) nt val inp.nextInt 10 12 13 14 15 16 17 Operations tester-ner Operations ) int restester.linearSearchlinear,val) if (res --1) 19 20 21 System.out println (Value not found in array) 23 24 25 26 27 28 29 30 31 32 System.out println (Value found in array at index: +res) System.out.printin (n- - - restester.binarySearch (binary, val): if (res ---1) inary Search -hin ine: 66/ 68 col: 5 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: Tester.mainTester.java - C HamaRaDesktop ggJan Sort - Gean Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations.jevaMergeSort.java X Tester java res tester.binarySearch (binary, val) If(res 1) 34 35 36 37 38 39 40 System.out-println(Value not found in array): else System.out-println(Value found in array at index: +res) 42 43 System.out.println (n- System.out.printinn-- - tester.selectionsort (selection) Syatem.out.println (n- tester-printArray (selection) -Selection Sort -) 45 47 4 8 49 50 51 52 53 54 Syatem.out.println (n- tester.mergeSort (arrayMerge,0, arrayMerge.length-1) Merge Sort---n) teater printArray arrayMerge) System.out.println (n System.out.printinn-- - tester.insertionsort (insertion) System.out.println (n tester-printArray (insertion) -Insertion Sort -) 56 57 58 59 60 61 62 63 64 System.out.println (n--- tester.bubbleSort (bubble) Bubble Sort ine: 70/71 col: 32 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype Java scope: unknownTester.java - C HamaRaDesktop ggJan Sort - Gean Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations.jevaMergeSort.java X 39 40 41 ร์2 43 ร์ร์ 45 ร์6 47 48 Tester java System.out println (Value found in array at index: +res) System.out.printin (n tester.selectionSort (selection) cester printArray (gelection) System.out.printinn 50 51 52 53 cester mergesort (arrayMerge, arrayMerge.length-1) System.out.printin (n tester printArray(arrayMerge) After Sorting -n) System.out.printin (n tester.insertionSort (insertion) 56 57 58 59 60 61 62 63 69 65 cester printArray (insertion) System.out.printinn- cester.bubblesort (bubble) n 67 69 end of code //screenshot of code and outputl 70 71 ine: 70/71 col: 32 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype Java scope: unknownerations java - C HamaRa\Desktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations javaTester. jeve X //operations.Java iport Java.utii.scanner class Operations 3 //method to print array of passed argument array public void printArray inti ar) int i-0; int len -ar.length 10 12 13 14 15 16 17 18 19 20 21 System.out-print (ar[i]) il(i < len- 1) Syot cem.out.print( ): public int linearScarch(intar,int val) int i; int lenar.length: int ind-1 /linearly search for element 23 24 25 2 6 27 28 29 30 31 32 if (val-ar[i]) ind -i break: return ind; ine: 11/189 col: 9 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: Oerations java - C HamaRaDesktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations javaTester. jeve X 32 return ind: 3ร์ 35 36 37 38 39 40 41 42 ร์3 public int binerySearch (intlar,int val) int ind1: int len-ar.length: int left 0: int rightlen1 int middle: //check for the value at middle of array while (left -right) 45 ร์6 47 48 49 S0 51 52 53 54 middle-lcft (right-left) /2: if (ar [middle] val) ind = middle; break: /ir middle element isval then the value might be second half 1I (ar [middle]< val) leftmiddle1: 56 57 S8 59 60 61 62 63 64 //it middle element 19 val then the value might be 1irst half clsc rightmiddle1 return ind; ine: 11/189 col: 9 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: Oerations java - C HamaRaDesktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations javaTester. jeve X 64 65 public void selectionsort (inti ar) 67 68 69 70 71 72 73 74 75 76 int i,j: int min: int lenar.length: int temp: // election ort min-i: /assume i th elenent as minimum element find the min value from i to len 78 79 80 if (ar[j] < ar[min]) min 82 83 84 85 86 87 //swap with min element cemp ar ar [min]-temp: 89 90 91 public void merge (int ari,int left,int middle,int right) 93 9ร์ 95 96 int lenimiddle- left1 int len2 - rightmiddle: intti leftArraynew intileni intll rightArray - ne int[ilen2] int i,j,k: ine: 11/189 col: 9 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: Oerations java - C HamaRaDesktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations-javaTesterjava 94 95 96 97 98 int [ ] rightArray= new int [len2]; int 1,,k: /copy le values to leftArray (temp array 100 101 102 103 104 105 106 107 108 109 110 leftArraylil arlleft i]: //copy len2 values to rightArray (temp array) rightArreyi]ar[middle 1 +i: kleft: /Pmerge sort the to temp arrays 112 113 114 115 116 if (1eftArray[i] <-rightArray[j]) arklertArray[i1 i+t: 118 119 120 121 122 123 12ร์ 125 126 else ark)rightAyi: while i < len1) ine: 11/189 col: 9 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: Oerations java - C HamaRa\Desktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Serations java - C HamaRaDesktop CheggJan Sort - Geany Eile Edt Search View Document Project Build Iools Help New Open Save Save AllRevertClose Back Forward Compile Build cute Color Chooser Find Jump to Quit Operations javaTester. jeve X 157 158 159 160 161 162 163 164 165 166 167 168 169 170 key ari 1-1; while (0&& ar) > key) eri+1]-key: public void bubbleSort (int[] ar) int i,j int lenar.length: int temp: for (1-0; i < len; i++) 172 173 179 175 176 if(ar[j >ari+1]) 178 179 180 181 182 183 184 185 186 187 188 189 temp ar ri)ari+1] arj+1]-temp: //End of operations.java ine: 11/189 col: 9 sel: 0 INS TAB mode: CRLF encoding: UTF-8 filetype: Java scope: OCWindows SYSTEM32cmd.exe G-s. Enter value to search:3 Linear Search alue found in array at index: 2 Binary Search alue found in array at index: 1 ---Selection Sort-_--_--_ After Sorting 1.3 5.6.7.8.9 . 27. 39. 87 2:8:2 : Merge Sort After Sorting --- Insertion Sort After Sorting Bubble Sort ---After Sorting - - . 3.5.6.7.8.9 . 27 . 39.87 program exited with code:83 ss any key to continue . . .

Add a comment
Know the answer?
Add Answer to:
In Java, write your own methods to do the following: LinearSearch BinarySearch SelectionSort MergeSort InsertionSort BubbleSort...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA Write a program which will read a text file into an ArrayList of Strings. Note...

    JAVA Write a program which will read a text file into an ArrayList of Strings. Note that the given data file (i.e., “sortedStrings.txt”) contains the words already sorted for your convenience. • Read a search key word (i.e., string) from the keyboard and use sequential and binary searches to check to see if the string is present as the instance of ArraryList. • Refer to “SearchInt.java” (given in “SearchString.zip”) and the following UML diagram for the details of required program...

  • Write Java program to compare time consumed by linear search and binary search to search for...

    Write Java program to compare time consumed by linear search and binary search to search for non-exit element in arrays of length 1000, 100000,500000,1000000. Hints: - Use Random class, method nextInt(a.length) to generate random numbers. - Select an element that is greater than a.length. - Use Arrays.sort(a) to sort the array before using binarySearch.

  • Program with generic merge sort and binary search method help. The programming language I'm using is...

    Program with generic merge sort and binary search method help. The programming language I'm using is Java. This program should show understanding generic merge sort methods and generic binary search methods in java. The execution should include at least 5 found items including one from the first three items in the sorted array and one from the last three items in the sorted array as well as at least two items not found Create a generic merge sort method that...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  • Include the blackbox output done with C# microsoft visual studios software. write a C# program to...

    Include the blackbox output done with C# microsoft visual studios software. write a C# program to sort a parallel array that consists of customer names and customer phone numbers. The solution should be in ascending order of customer names. For instance, if the input is string[] custNames- { "ccc", "ddd", "aaa", "bbb" }; stringl] custIds687-3333", "456-4444", "789-1111", "234-2222" ; then, the solution is string[] string[] custNames- { "aaa", "bbb", "ccc", "ddd" }; custIds"789-1111", "234-2222", "687-3333", "456-4444"]; There are some restrictions:...

  • Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch...

    Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch algorithms as follows: Suppose list is an array of 2500 elements. 1. Use a random number generator to fill list; 2. Use a sorting algorithm to sort list; 3. Search list for some items as follows: a) Use the binary search algorithm to search list (please work on SearchSortAlgorithms.java and modify the algorithm to count the number of comparisons) b) Use the sequential search...

  • please do this lab in Java in given instructions by tomorrow morning. TkA CHRI - TREE...

    please do this lab in Java in given instructions by tomorrow morning. TkA CHRI - TREE UTH A HEAPOF PRESDNS CENETH CSC 236-Lab 6 (2 programs) trees 1. Given the two binary trees below: 14 18 16) Write a method called swapSubtrees, which swaps all of the left and right subtrees in the above binary trees. Add this method to the class BinaryTree and create a program to test this method for these 2 trees. Show the original trees and...

  • Assignment on Java programing 1. Write programs for the following exercises in Java. Each file should...

    Assignment on Java programing 1. Write programs for the following exercises in Java. Each file should have short description of the implemented class and for files with main method the problem it is solving. Make sure your files have appropriate names. Programs should write output to the Console. b) BST: Implement Binary Search Tree ADT with insert(int key), delete(int key), Node find(int key), and in-order traverse() where it prints the value of the key. Your operations should use recursion. The...

  • Need assistance with this problem. This is for a java class and using eclipse. For this...

    Need assistance with this problem. This is for a java class and using eclipse. For this assignment we’ll be doing problems 21.3 and 21.4 from your textbook. Problem 21.3 asks you to write a generic method that removes duplicate items from an ArrayList. This should be fairly straightforward. Problem 21.4 asks you to implement insertion sort within a generic method. Insertion sort is described in detail on pages 250-252 of your textbook. You can write your two methods in a...

  • IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity...

    IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity with simple binary search trees. 1. Begin this lab by implementing a simple class that represents a "node” in a binary search tree, as follows. public class MyTreeNode<t extends Comparable<T>> { public T data; public MyTreeNode<T> leftchild; public MyTreeNode<T> rightChild; public MyTreeNode<T> parent; 2. Have the second member of your pair type in the code for the simple binary search tree interface. public interface...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT