Created
January 8, 2014 23:09
-
-
Save rice2007/8326450 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package labone.insertionsort; | |
import java.util.Scanner; | |
public class InsertionSort { | |
public static void linearSearch(int[] array, int key) { | |
insertionSort(array); | |
boolean foundFlag = false; | |
for (int i = 0; i < array.length; i++) { | |
if (array[i] == key) { | |
System.out.println(Integer.toString(key) + " is at index " | |
+ Integer.toString(i) + "."); | |
foundFlag = true; | |
} | |
} | |
if (!foundFlag) System.out.println("The entered value was not found."); | |
return; | |
} | |
public static void binarySearch(int[] array) { | |
insertionSort(array); | |
} | |
private static int[] insertionSort(int[] array) { | |
int key; | |
int i; | |
for (int j = 1; j < array.length; j++) { | |
i = j; | |
while(i > 0 && array[i - 1] > array[i]) { | |
key = array[i]; | |
array[i] = array[i - 1]; | |
array[i - 1] = key; | |
i--; | |
} | |
} | |
System.out.println(); | |
return array; | |
} | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
int n = 32; | |
int[] array = new int[n]; | |
int key = Integer.parseInt(scan.next()); | |
for (int i = 0; i < array.length; i++) { //Prints the unsorted array | |
array[i] = (int) (Math.random() * n + 1); | |
if (i < array.length - 1) { | |
System.out.print(array[i] + ", "); | |
} | |
else System.out.println(i); | |
} | |
linearSearch(array, key); | |
scan.close(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment