0% found this document useful (0 votes)
34 views

Search and Sort Algorithm

Uploaded by

vidhibandekar2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Search and Sort Algorithm

Uploaded by

vidhibandekar2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Array Searching and Sorting Programs

• Searching from start of an array from 0th index of array

• Process continues checks the existence of the given data in the


list of array elements one by one until the end of the array is
reached

• Also called Sequential search

1.
public class LinearSearchExample1{
public static int linearSearch(int[] arr, int key,int key1){
for(int i=0;i<arr.length;i++){
if(arr[i] == key||arr[i]==key1){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 20;
int key1=30;
System.out.println(key+" is found at index: "+linearSearch(a1, key,key1));
}
}

2. import java.util.Scanner;

class LinearSearchExample2
{
public static void main(String args[])
{
int c, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array= new int[n];

System.out.println("Enter those " + n + " elements");

for (c = 0; c < n; c++) //filling the elements of the array


array[c] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

for (c = 0; c < n; c++) //to iterate over the array and search for the key
element
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}

/*Write a program in Java to store 20 numbers in a Single Dimensional Array


(SDA). Display the numbers which are prime.
Sample Input:

n[0] n[1] n[2] n[3] n[4] n[5] ... n[16] n[17] n[18] n[19]
45 65 77 71 90 67 ... 82 19 31 52
Sample Output: 71, 67, 19, 31*/
import java.util.*;

public class SDAPrimeNumbers


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];

System.out.println("Enter 20 numbers");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}

System.out.println("Prime Numbers:");
for (int i = 0; i < arr.length; i++) {

int c = 0;//counter variable


for (int j = 1; j <= arr[i]; j++) {
if (arr[i] % j == 0) {
c++;
}
}

if (c == 2)
System.out.print(arr[i] + ", ");
}
}
}
4.
// Java program to find minimum (or maximum)
// element in an array.
//import java.io.*;

class ArrayMinMax {

static int getMin(int arr[], int n)


{
int res = arr[0];

for (int i = 1; i < n; i++)


res = Math.min(res, arr[i]);
return res;
}

static int getMax(int arr[], int n)


{
int res = arr[0];

for (int i = 1; i < n; i++)


res = Math.max(res, arr[i]);
return res;
}

public static void main (String[] args)


{
int arr[] = { 12, 1234, 45, 67, 1 };
int n = arr.length;//n=5
System.out.println( "Minimum element"+ " of array: " + getMin(arr, n));
System.out.println( "Maximum element"+ " of array: " + getMax(arr, n));
}
}

5.
/*Write a program in Java to store 20 numbers (even and odd numbers) in a
Single Dimensional Array (SDA). Calculate and display the sum of all even
numbers and all odd numbers separately.*/
import java.util.Scanner;
public class SDAOddEvenSum
{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);


int arr[] = new int[20];

System.out.println("Enter 20 numbers");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}

int oddSum = 0, evenSum = 0;

for (int i = 0; i < arr.length; i++) {


if (arr[i] % 2 == 0)
evenSum += arr[i];
else
oddSum += arr[i];
}

System.out.println("Sum of Odd numbers = " + oddSum);


System.out.println("Sum of Even numbers = " + evenSum);
}
}
---------------------------------------------------------------------------------------------------------
/*Write a program in Java to store 10 numbers (including positive and
negative numbers) in a Single Dimensional Array (SDA).
*Display all the negative numbers followed by the positive numbers without
changing the order of the numbers.
Sample Input:

n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]
15 21 -32 -41 54 61 71 -19 -44 52
Sample Output: -32, -41, -19, -44, 15, 21, 54, 61, 71, 52*/

import java.util.Scanner;

public class SDANumbers


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[10];//array initialisation and declaration

System.out.println("Enter 10 numbers");//filling the array with array


elements
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}

for (int i = 0; i < arr.length; i++) {


if (arr[i] < 0)
System.out.print(arr[i] + ", ");
}

for (int i = 0; i < arr.length; i++) {


if (arr[i] >= 0)
System.out.print(arr[i] + ", ");
}
}
}
________________________________________________________________
• Binary Search
• Searching in a minimum possible time
• Complete array is divided into 2 halves and the desired element may
be present in first half or the second half
• Search operation is done by dividing the array elements into halves
and is termed as Binary search
• Can be performed only when sorted in ascending or descending order
• Compares with the middle element, if middle element is small then
search continues in first half
• Middle element of either half is compared with the element to be
searched
• Process is repeated until the element id found or the array elements
have exhausted in with the halves

• Step VI In case the element not found then repeat the process from Step III unless First
is greater than the last
• Finally the process will be completed resulting in “Search is unsuccessfull”
• Repeatedly select the smallest key in the remaining
unsorted array and bring it to its right position
• In an unsorted array the first smallest will be
brought to first position second smallest to
second position third smallest to third position and so on

-Selection Sort Algorithm


In this tutorial, you will learn about the selection sort algorithm and its
implementation in Python, Java, C, and C++.
Selection sort is a sorting algorithm that selects the smallest element from an
unsorted list in each iteration and places that element at the beginning of the
unsorted list.
Working of Selection Sort
1. Set the first element as minimum.

Select first element as


minimum
2. Compare minimum with the second element. If the second element is
smaller than minimum, assign the second element as minimum.

Compare minimum with the third element. Again, if the third element
is smaller, then assign minimum to the third element otherwise do
nothing. The process goes on until the last element.

Compare minimum with the


remaining elements
3. After each iteration, minimum is placed in the front of the unsorted

list. Swap the first with


minimum
4. For each iteration, indexing starts from the first unsorted element.
Step 1 to 3 are repeated until all the elements are placed at their
correct positions.
The first
iteration The
second iteration

The third iteration


The fourth
iteration
// Java program for implementation of Selection Sort
//int arr[] = {64,25,12,22,11};
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;//n=5

// One by one move boundary of unsorted subarray


for (int i = 0; i < n-1; i++)//outer loop
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)//inner loop
if (arr[j] < arr[min_idx])//25<64//12<25
min_idx = j;//min_idx=1

// Swap the found minimum element with the first


// element
int temp = arr[min_idx];//temp=arr[4]//temp=11
arr[min_idx] = arr[i];//arr[4]=64
arr[i] = temp;//arr[0]=11
}
}

// Prints the array


void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}

// Driver code to test above


public static void main(String args[])
{
SelectionSort ob = new SelectionSort();//objectCreation
int arr[] = {64,25,12,22,11};
ob.sort(arr);//invoking the method sort
System.out.println("Sorted array");
ob.printArray(arr);
}
}
_Bubble Sort Algorithm

• Compare two adjoining values and exchange them if they are not in
proper order
• This process is repeated for every pair of adjoining elements in the array
• In every pass, the heaviest element settles as its appropriate position in
the bottom
• Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.
• Example:
• First Pass:
• ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two
elements, and swaps since 5 > 1.
• ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
• ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in
order (8 > 5), algorithm does not swap them.
• Second Pass:
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
• ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to
know it is sorted.
• Third Pass:
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
// Java program for implementation of Bubble Sort
//int arr[] = {64, 34, 25, 12, 22, 11, 90};
class BubbleSort
{
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)//Pass
for (int j = 0; j < n-i-1; j++)// Iteration
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
/* Prints the array */
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method to test above


public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
________________________________________________________________
/*Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the
elements before.
Move the greater elements one position up to make space for the swapped
element.*/

public class InsertionSort {


public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");


for(int i:arr1){
System.out.print(i+" ");
}
} }

You might also like