Array Java 10th
Array Java 10th
Linear search is used to search a key element from multiple elements, stored in Array.
Algorithm:
Let's see an example of linear search in java where we are going to search an element
sequentially from an array.
1. import java.util.Scanner;
2.
3. class LinearSearchExample
4. {
5. public void main()
6. {
7. int c, n, search;
8.
9. Scanner in = new Scanner(System.in);
10. System.out.println("Enter number of elements");
11. n = in.nextInt();
12. int array[ ] = new int[n];
13.
14. System.out.println("Enter those " + n + " elements");
15.
16. for (c = 0; c < n; c++)
17. array[c] = in.nextInt();
18.
19. System.out.println("Enter value to find");
20. search = in.nextInt();
21.
22. for (c = 0; c < n; c++)
23. {
24. if (array[c] == search) /* Searching element is present */
25. {
26. System.out.println(search + " is present at location " + (c + 1) + ".");
27. break;
28. }
29. }
30. if (c == n) /* Element to search isn't present */
31. System.out.println(search + " isn't present in array.");
32. }
33. }
Output:
SORTING IN ARRAYS
We can create a java program to sort array elements using bubble sort. Bubble sort
algorithm is known as the simplest sorting algorithm.
In bubble sort algorithm, array is traversed from first element to last element. Here,
current element is compared with the next element. If current element is greater than
the next element, it is swapped.
Bubble sort program for sorting in Ascending Order:
import java.util.Scanner;
class BubbleSortExample
{
public void main()
{
int num, i, j, temp;
Scanner input = new Scanner(System.in);
In order to sort in descending order we just need to change the logic array[j] >
array[j+1] to array[j] < array[j+1] in the above program. Complete code as follows:
import java.util.Scanner;
class BubbleSortExample
{
public void main()
{
int num, i, j, temp;
Scanner input = new Scanner(System.in);
Output: