Array

29. Program

(Imp_Q) Write a program for right shift by 2 elements in array ?

class M { public static void main(String args[]) { int[] a = {2, 4, 4, 2, 4, 7, 4, 5}; for(int i = 0; i < a.length; i++) { System.out.print(a[i] + ","); } System.out.println(); int temp1 = a[a.length-2], temp2 = a[a.length-1]; for(int i = a.length-1; i > 1; i--) { a[i] = a[i-2]; } a[0] = temp1; a[1] = temp2; for(int i = 0; i < a.length; i++) { System.out.print(a[i] + ","); } System.out.println(); } }

30. Program

(M.Imp_Q) Write a program for binary search to an array ?

class N { public static void main(String args[]) { int[] a = {3, 9, 20, 45, 50, 200, 401, 500, 600, 808, 909}; int i = binarySearch(a, 50); System.out.println(i); } private static int binarySearch(int[] a, int element) { int index = -1; int begin = 0; int last = a.length - 1; int mid; while(last >= begin) { mid = (begin + last) / 2; if(a[mid] == element) { index = mid; break; } if(a[mid] > element) { last = mid - 1; } else { begin = mid + 1; } } if(index == -1) { if(element < a[0]) { return index; } int j = -1; //counter for(int i = 0; i < a.length; i++) { j--; if(a[i] < element && a[i+1] > element) { break; } } if(element > a[a.length - 1]) { j--; } index = j; } return index; } }

Page....