ARRAYS

Example includes: sequential search, finding maximum value, insertion sort, binary search

package packArraySeqSearch;

public class TestSeqSearch {

public static void main(String[] args) {

int[] A = { 2, 4, 7, 8, 2, 1, 5};

showArray(A);

int answer = seqSearch(A, 11);

System.out.println("answer is: " + answer);

int theBigGuy = locateMax(A);

System.out.println("position of max is: " + theBigGuy +

" and the value is: " + A[theBigGuy] );

sortByInsertion(A);

int sol = binarySearch(A, 8);

System.out.println(sol);

}//end main

public static void showArray (int[] A) {

for(int n=0; n<A.length; n++) {

System.out.print(" A[" + n + "]= " + A[n]);

}

System.out.println("\n");

}//end showArary

public static int seqSearch(int[] B, int searchValue) {

int i=0;

boolean found= false;

int pos = -1;

while ((found == false) & (i < B.length)) {

if (B[i]==searchValue) {

found = true;

pos = i;

}

i++;

}

return pos;

}

public static int locateMax(int[] B) {

int pos = 0;

for (int i=1; i<B.length; i++){

if (B[pos] < B[i]) {

pos = i;

}

}

return pos;

}

public static int locateMax2(int[] B, int size) {

int pos = 0;

for (int i=0; i < size; i++){

if (B[pos] < B[i]) {

pos = i;

}

}

return pos;

}

public static void sortByInsertion(int[] A) {

//use insertion sort (max goes to last pos.)

int posMax=0;

int temp;

for (int theLast= A.length-1; theLast>1; theLast--) {

posMax = locateMax2(A, theLast);

temp = A[theLast];

A[theLast] = A[posMax];

A[posMax] = temp;

showArray(A);

}

}

public static int binarySearch(int[] A, int searchValue) {

int first=0, last=A.length-1;

int middle=0;

int result=0;

boolean found= false;

while ((first <= last) & (found==false)) {

middle =(int) (first + last)/2;

if (A[middle] == searchValue){

found = true;

}

else if (A[middle] < searchValue){

first = middle + 1;

}

else {

last = middle - 1;

}//end else------

}//end while ------

if (found == false)

result = -1;

else

result = middle;

return result;

}

}