Logout

Home


Sort and Binary Search Example

 
1 
 2 package sorting.and.searching.phase.pkg1;
 3 
 4 /**
 5  *
 6  * @author johnrayworth
 7  */
 8 public class BinarySearchClass {
 9 
10     public static void main(String[] args) {
11         int[] intArr = {12, 234, 66, 123, 234, 567, 10100, 34, 23, 8888, 9999};
12 
13         
14         for(int i = 0; i < intArr.length; i++){
15             System.out.print(intArr[i] + ", ");
16         }
17         System.out.println("");
18         
19         selectionSort(intArr);
20         
21         for(int i = 0; i < intArr.length; i++){
22             System.out.print(intArr[i] + ", ");
23         }
24         System.out.println("");
25 
26         int result = binarySearch(intArr, 123);
27         if (result != -1) {
28             System.out.println("The result was indeed found at "
29                     + "index number " + result);
30         } else {
31             System.out.println("The result was not found.");
32         }
33     }
34 
35     public static int binarySearch(int[] arr, int key) {
36         int low = 0;
37         int high = arr.length - 1;
38         while (low <= high) {
39             int mid = (low + high) / 2;
40             if (arr[mid] == key) {
41                 return mid;
42             } else if (arr[mid] < key) {
43                 low = mid + 1;
44             } else {
45                 high = mid - 1;
46             }
47         }
48 
49         return -1;
50     }
51 
52     public static void selectionSort(int[] intArray) {
53         for (int i = 0; i < intArray.length - 1; i++) {
54             int minIndex = i;      // Assumed index of smallest remaining value.
55             for (int j = i + 1; j < intArray.length; j++) {
56                 if (intArray[j] < intArray[minIndex]) {
57                     minIndex = j;  // Remember index of new minimum
58                 }
59             }
60             if (minIndex != i) {
61                 //Exchange current element with smallest remaining.
62                 //But note that this only happens once each outer loop iteration, at the end of the inner loop's looping
63                 int temp = intArray[i];
64                 intArray[i] = intArray[minIndex];
65                 intArray[minIndex] = temp;
66             }
67         }
68     }
69 
70 }
71