6
1. Write Java programs that use both recursive and non- recursive functions for implementing the following searching methods: (a) Linear search (b) Binary search Linear search (a) The simplest form of a search is the linear search. This technique is meant for searching a particular item in an unsorted data set in a sequential manner until the desired data item is found. Linear search is easy to write and efficient for short lists, but inefficient for long ones. To find any element in a long array (list), there are far more efficient methods, provided that the array is sorted. A program for linear search is as follows. Program 1(a): Iterative Linear search class LinearSearchDemo { static Object[] a = { 89, 45, 175, 7, 50, 43, 126, 90 }; static Object key = 126; public static void main(String args[]) { if( linearSearch() ) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); }

Java Sample Programs

Embed Size (px)

DESCRIPTION

has sample programs for java

Citation preview

1. Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods:

1. Linear search (b) Binary search Linear search 1. The simplest form of a search is the linear search. This technique is meant for searching a particular item in an unsorted data set in a sequential manner until the desired data item is found. Linear search is easy to write and efficient for short lists, but inefficient for long ones. To find any element in a long array (list), there are far more efficient methods, provided that the array is sorted. A program for linear search is as follows.

Program 1(a): Iterative Linear search

class LinearSearchDemo { static Object[] a = { 89, 45, 175, 7, 50, 43, 126, 90 }; static Object key = 126; public static void main(String args[]) { if( linearSearch() ) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); } static boolean linearSearch() { for( int i=0; i high ) return false; int mid = (low + high)/2; int c = ((Comparable)key).compareTo(a[mid]); if( c < 0) return binarySearch(low, mid-1); else if( c > 0) return binarySearch(mid+1, high); else return true; } }

OUTPUTUP found in the list