/home/caleb/ASDV-Java/Assignments/lab17_CalebFontenot/src/main/java/com/calebfontenot/lab17_calebfontenot/Lab17_CalebFontenot.java |
nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/$
package com.calebfontenot.lab17_calebfontenot;
@author
public class Lab17_CalebFontenot {
public static void main(String[] args)
{
final int NUM_TO_SEARCH_FOR = 2;
int[] originalArray = new int[]{420, 41, 7, 2, 26, 2243};
System.out.print("Original array: ");
printArray(originalArray);
selectionSort(originalArray);
System.out.print("Sorted array: ");
printArray(originalArray);
System.out.println("Binary Search");
System.out.println("-----------------------");
System.out.println("binarySearchWhile() returns: " + binarySearchWhile(originalArray, NUM_TO_SEARCH_FOR));
isInArray(binarySearchWhile(originalArray, NUM_TO_SEARCH_FOR), NUM_TO_SEARCH_FOR);
System.out.println("binarySearchFor() returns: " + binarySearchFor(originalArray, NUM_TO_SEARCH_FOR));
isInArray(binarySearchFor(originalArray, NUM_TO_SEARCH_FOR), NUM_TO_SEARCH_FOR);
}
public static void isInArray(int arrayResult, int searchQuery)
{
if (arrayResult == 0) {
System.out.println(searchQuery + " is in the array.");
} else {
System.out.println(searchQuery + " is not in the array.");
}
}
public static int[] selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; ++i) {
for (int j = i; j < arr.length; ++j) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static void printArray(int[] arr)
{
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static int binarySearchWhile(int[] ar, int key)
{
int low = 0;
int high = ar.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < ar[mid]) {
high = mid - 1;
} else if (key == ar[mid]) {
return mid;
} else {
low = mid + 1;
}
}
return 1;
}
public static int binarySearchFor(int[] ar, int key)
{
int low = 0;
int high = ar.length - 1;
for (low = 0; high >= low;) {
int mid = (low + high) / 2;
if (key < ar[mid]) {
high = mid - 1;
} else if (key == ar[mid]) {
return mid;
} else {
low = mid + 1;
}
}
return 1;
}
}