Advertisement
Guest User

Sorting and Searching V2

a guest
Sep 20th, 2016
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package chapter7;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5.  
  6. public class SortingAndSearching2 {
  7.  
  8.     private static void print(int x[], int columnsize, int numPerLine) {
  9.         for (int i = 0; i < x.length; i++) {
  10.             System.out.printf("%" + columnsize + "d", x[i]);
  11.             if ((i + 1) % numPerLine == 0 || (i + 1) == x.length)
  12.                 System.out.println();
  13.         }
  14.     }
  15.  
  16.     private static int[]generateJunk(int count) {
  17.         int values[] = new int[count];
  18.         for (int i = 0; i < values.length; i++) {
  19.             values[i] = (int) (Math.random() * 100) + 1;
  20.         }  
  21.         return values;
  22.     }
  23.    
  24.  
  25.     public static void main(String[] args) {
  26.  
  27.         int values[] = generateJunk(100);
  28.         System.out.println("Random Junk!");
  29.         print(values, 5, 10);
  30.         System.out.println();
  31.  
  32.  
  33.         // linear search the junk
  34.         Scanner input = new Scanner(System.in);
  35.         int key;
  36.         do {
  37.             System.out.print("Enter key: ");
  38.             key = input.nextInt();
  39.             int index = LinearSearch.linearSearch(values, key);
  40.             if (index < 0) {
  41.                 System.out.println("Not in Array");
  42.             } else {
  43.                 System.out.println(key + " found in position " + index);
  44.             }
  45.         } while (key >= 0);
  46.        
  47.         // Duplicate the junk
  48.         int duplicate[] = Arrays.copyOf(values, values.length);
  49.  
  50.  
  51.         // Sort the Duplicate Junk
  52.         Arrays.sort(duplicate);
  53.         System.out.println("Sorted Junk!");
  54.         System.out.println(Arrays.toString(duplicate));
  55.         System.out.println();
  56.  
  57.         // Now Binary Search the dups array
  58.         do {
  59.             System.out.print("Enter key: ");
  60.             key = input.nextInt();
  61.             int index = Arrays.binarySearch(duplicate, key);
  62.             System.out.println(index);
  63.             if (index < 0) {
  64.                 System.out.println("Not in Array, but key could be placed in position " + (-index - 1));
  65.             } else {
  66.                 System.out.println(key + " found in position " + index);
  67.             }
  68.         } while (key >= 0);
  69.        
  70.         input.close();
  71.     }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement