Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Data Structures Using JAVA Semester IV

UNIT – V
SORTING AND SEARCHING
SORTING:
“Sorting is the process of arranging the elements in a list or collection
in increasing or decreasing order of some property”. It involves comparisons
of the data items among themselves and exchanging or replacing some of
them to achieve an arrangement of the items in the desired order.

Sorting can be classified into two categories, internal sorting and


external sorting, depending on where the input data resides, either in the
internal memory or in the external memory.

PASSES:
Only two items can be compared at a time. For comparing all the
elements in a given list, we have to traverse the entire list from left to right,
taking two adjacent items at a time and perform an exchange between two
items if necessary. This traversal of the list each time is called a pass.

SORTING TECHNIQUES:
There are different types sorting techniques. They are:

1. Selection Sort
2. Bubble Sort
3. Insertion Sort
4. Merge Sort
5. Quick Sort
6. Heap Sort

SELECTION SORT:
One of the easiest ways to sort elements is by selection sort.
Beginning with the first element in the list of elements, a search is
performed to locate the element which is smallest.

The selection sort algorithm sorts an array by repeatedly finding the


next smallest element and placing it in its next proper position (within the
desired order) continues until all elements have been sorted in ascending
order.

The algorithm maintains two subarrays in a given array:

1. The subarray which is already sorted.


Data Structures Using JAVA Semester IV

2. Remaining subarray which is unsorted.

In every, iteration of selection sort the minimum element (considering


ascending order) from the unsorted subarray is picked and moved to the
sorted subarray.

Program:

import java.io.*;

public class SelectionSort {

public static void main(String a[ ]) throws IOException {

int i, size;

int array[ ];

DataInputStream in = new DataInputStream(System.in);

System.out.println("Enter array size:");

size = Integer.parseInt(in.readLine( ));

array = new int[size];

System.out.println("Enter any "+size+" integers:");


Data Structures Using JAVA Semester IV

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

System.out.print("Enter "+(i+1)+" number:");

array[i] = Integer.parseInt(in.readLine());

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

System.out.println("Values Before the sort:\n");

for(i = 0; i < array.length; i++)

System.out.print( array[i]+" ");

System.out.println( );

selection_srt(array, array.length);

System.out.print("Values after the sort:\n");

for(i = 0; i <array.length; i++)

System.out.print(array[i]+" ");

System.out.println( );

public static void selection_srt(int array[ ], int n)

for(int x=0; x<n; x++)

int index_of_min = x;

for(int y=x; y<n; y++)

if(array[index_of_min]>array[y])

index_of_min = y;

} }

int temp = array[x];


Data Structures Using JAVA Semester IV

array[x] = array[index_of_min];

array[index_of_min] = temp;

Output:

Enter array size: 5

Enter any 5 integers:

Enter 1 number: 9

Enter 2 number: 5

Enter 3 number: 1

Enter 4 number: 10

Enter 5 number: 2

Selection Sort

Values before the sort: 9 5 1 10 2

Values after the sort: 1 2 5 9 10

BUBBLE SORT:
Bubble sort is also known as exchange sort. Bubble Sort is the
simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.

Algorithm:

1. Compare each pair of adjacent elements from the beginning of an


array and, if they are in reversed order, swap them.
2. If at least one swap has been done, repeat step 1.
Data Structures Using JAVA Semester IV

/* Program to implement Bubble sort */

import java.io.*;

public class BubbleSort {

public static void main(String a[ ]) throws IOException {

int i,size;

int array[ ];

DataInputStream in = new DataInputStream(System.in);


System.out.println("Enter array size:");

size = Integer.parseInt(in.readLine( ));

array = new int[size];

System.out.println("Enter any "+size+" integers:");

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

System.out.print("Enter "+(i+1)+" number:");


Data Structures Using JAVA Semester IV

array[i] = Integer.parseInt(in.readLine( ));

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

System.out.println("Values Before the sort:\n");

for(i = 0; i < array.length; i++)

System.out.print( array[i]+" ");

System.out.println( );

bubble_srt(array, array.length);

System.out.println("\nValues after the sort:\n");

for(i = 0; i <array.length; i++)

System.out.print(array[i]+" ");

System.out.println( );

public static void bubble_srt( int a[ ], int n ) {

int i, j,t=0;

for(i = 0; i < n; i++) {

for(j = 1; j < (n-i); j++) {

if(a[j-1] > a[j]) {

t = a[j-1]; a[j-1]=a[j]; a[j]=t;


} } } } }

INSERTION SORT:
Insertion sorting algorithm is similar to bubble sort. But insertion sort
is more efficient than bubble sort because in insertion sort the elements
comparisons are less as compare to bubble sort. In insertion sorting
algorithm compare the value until all the prior elements are lesser than
compared value is not found.

This algorithm is more efficient than the bubble sort .Insertion sort is
a good choice for small values and for nearly-sorted values.
Data Structures Using JAVA Semester IV

/* Program to implement Insertion sort */

import java.io.*;

public class InsertionSort {

public static void main(String a[ ]) throws IOException {

int i,size;

int array[ ];

DataInputStream in = new DataInputStream(System.in);

System.out.println("Enter array size:");

size = Integer.parseInt(in.readLine());

array = new int[size];

System.out.println("Enter any "+size+" integers:");

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

System.out.print("Enter "+(i+1)+" number:");

array[i] = Integer.parseInt(in.readLine( ));


Data Structures Using JAVA Semester IV

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

System.out.println("Values Before the sort:\n");

for(i = 0; i < array.length; i++)

System.out.print( array[i]+" ");

System.out.println();

insertion_srt(array, array.length);

System.out.println("\nValues after the sort:\n");

for(i = 0; i <array.length; i++)

System.out.print(array[i]+" ");

System.out.println( );

public static void insertion_srt(int array[ ], int n) {

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

int j = i;

int B = array[i];

while ((j > 0) && (array[j-1] > B)) {

array[j] = array[j-1];

j--;

array[j] = B;

}}}

QUICK SORT:
Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a
comparison sort. The working of quick sort algorithm is depending on a
divide-and-conquer strategy. A divide and conquer strategy is dividing an
array into two sub-arrays. Quick sort is one of the fastest and simplest
sorting algorithms.
Data Structures Using JAVA Semester IV

Algorithm:

1. In quick sort algorithm pick an element from array of elements. This


element is called the pivot.
2. Then compare the values from left to right until a greater element is
finding then swap the values.
3. Again start comparison from right with pivot. When lesser element is
finding then swap the values.
4. Follow the same steps until all elements which are less than the pivot
come before the pivot and all elements greater than the pivot come
after it.
5. After this partitioning, the pivot is in its last position. This is called
the partition operation.
6. Recursively sort the sub-array of lesser elements and the sub-array
of greater elements.
Data Structures Using JAVA Semester IV

/* Program implement Quick sort */

import java.io.*;

public class QuickSort {

public static void main(String a[ ]) throws IOException {

int i,size;

int array[ ];

DataInputStream in = new DataInputStream(System.in);

System.out.println("Enter array size:");

size = Integer.parseInt(in.readLine( ));

array = new int[size];

System.out.println("Enter any "+size+" integers:");

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

System.out.print("Enter "+(i+1)+" number:");

array[i] = Integer.parseInt(in.readLine());

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

System.out.println("Values Before the sort:\n");

for(i = 0; i < array.length; i++)

System.out.print( array[i]+" ");

System.out.println( );

quick_srt(array, 0, array.length-1);

System.out.println("\nValues after the sort:\n");

for(i = 0; i <array.length; i++)

System.out.print(array[i]+" ");

System.out.println();

public static void quick_srt(int array[ ], int low, int n) {


Data Structures Using JAVA Semester IV

int lo = low;

int hi = n;

if (lo >= n) {

return;

int mid = array[(lo + hi) / 2];

while (lo < hi) {

while (lo<hi && array[lo] < mid) {

lo++;

while (lo<hi && array[hi] > mid) {

hi--;

if (lo < hi) {

int T = array[lo];

array[lo] = array[hi];

array[hi] = T;

}}

if (hi < lo) {

int T = hi;

hi = lo;

lo = T;

quick_srt(array, low, lo);

quick_srt(array, lo == low ? lo+1 : lo, n);

}
Data Structures Using JAVA Semester IV

HEAP SORT:
A heap is a complete binary tree which is represented using array or
sequential representation.

Every heap data structure has the following properties...

1. Ordering: Nodes must be arranged in a order according to values


based on Max heap or Min heap.
2. Structural: All levels in a heap must full, except last level and
nodes must be filled from left to right strictly.

Heap is classified as:

Max Heap: A Heap is a Max heap if all the nodes having value greater than
every children of the node.

Min Heap: A Heap is a Min heap if all the nodes having value lesser than
every children of the node.

Algorithm for Heap Sort:

1. Heapify the given elements.


2. Take first element into the sorted array.
3. Replace the first position with the last element.
4. Check whether the tree is a heap or not.
If yes then go to step-2
If no then go to step-1.

Using Max Heap:


Data Structures Using JAVA Semester IV

Program:
import java.util.Scanner;
public class HeapSort {
private static int N;
public static void sort(int arr[ ]) {
heapify(arr);
for (int i = N; i > 0; i--) {
swap(arr,0, i);
N = N-1;
maxheap(arr, 0);
}}
public static void heapify(int arr[ ]) {
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
maxheap(arr, i);
}
public static void maxheap(int arr[ ], int i) {
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i) {
swap(arr, i, max);
maxheap(arr, max);
}}
public static void swap(int arr[ ], int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[ ] args) {
Scanner scan = new Scanner( System.in );
System.out.println("Heap Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt( );
int arr[ ] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
Data Structures Using JAVA Semester IV

arr[i] = scan.nextInt( );
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println( );
} }
MERGE SORT:
Merge Sort is a Divide and Conquer algorithm. It divides input array
in two halves, calls itself for the two halves and then merges the two sorted
halves.

The following figure shows the merge sort process:


Data Structures Using JAVA Semester IV

Program:

import java.util.*;

public class MergeSort {

static int a[ ]=new int[15];

public class static void mergeSort(int low, int high) {

int mid;

if(low < high) {

if(mid+high)/2;

mergeSort(low, mid);

mergeSort(mid+1,high);

mergeSort(low, mid, high);

public static void merge(int low, int mid, int high) {

int b[ ]=new int[10], f=low, i=low, s=mid+1;

while((f<=mid)&&(s<=high)) {

if(a[f]<=a[s])

b[i]=a[f++];

else

b[i]=a[s++];

i++;

while(f<=mid)

b[i++]=a[f++];

while (s<=high)

b[i]=a[s++];

for(i=low;i<=high;i++)
Data Structures Using JAVA Semester IV

a[i]=b[i];

public static void main(String args[ ]) {

int size, I, low, high;

Scanner s=new Scanner(System.in);

System.out.print(“ENTER SIZE:”);

size=s.nextInt( );

System.out.println(“ENTER “+SIZE+”ELEMENTS:”);

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

a[i]=s.nextInt( );

low=0; high=size-1;

mergeSort(low,high);

System.out.println(“SORTED ORDER IS:”);

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

System.out.print(“ “+a[i]);

SEARCHING:
Search is a process of finding a value in a list of values .In other
searching is the process of locating given value position in a list of value.

Searching is classified into:

1. LINEAR SEARCH:
In Linear Search, we start with the first element of the list and
keep searching the whole list until we get the element from the list.
If a list is stored in computer’s memory as unsorted then to search
something in this list we will have to run Linear Search.

Algorithm:
Step 1: Read the search element from the user and compare, the search
element with the first element in the list.
Data Structures Using JAVA Semester IV

Step 2: If both are matching, then display "Given element found!!!" and
terminate the function

Step 3: If both are not matching, then compare search element with the
next element in the list.

Step 4: Repeat steps 3 and 4 until the search element is compared with the
last element in the list.

Step 5: If the last element in the list is also doesn't match, then display
"Element not found!!!" and terminate the function.

PROGRAM:
import java.util.*;

class LinearSearch {

public static void main(String args[ ])throws IOException {

int num[ ];

int key,pos,n,i;

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Enter size of array");

n=Integer.parseInt(br.readLine( ));

num=new int[n];

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


for(i=0;i<n;i++)
Data Structures Using JAVA Semester IV

num[i]=Integer.parseInt(br.readLine( ));
System.out.println("Enter the element to be searched");

key=Integer.parseInt(br.readLine());

pos=linearSearch(num,n,key);

if(pos==-1)

System.out.println("search is unsuccessful");

else {

System.out.println("search is successful");

System.out.println(key +" found at position "+(pos+1));


}

static int linearSearch(int arr[], n, key) {


int i;

i=0;

while(i<n) {

if(arr[i]=key)

return i;

if(arr[i]>key)

break;

i++;

return -1;

}}}

OUTPUT:
Enter size of array: 5

Enter 5 elements into array:

10 20 30 40 50

Enter the element to be searched: 40

Search is successful

40 found at position 4
Data Structures Using JAVA Semester IV

2. BINARY SEARCHING:
It is also known as half-interval search. The binary search
algorithm can be used with only sorted list of element.

The process of searching a sorted array by repeatedly dividing the


search interval in half is called “Binary Search”.

Algorithm:

Step 1: Read the search element from the user and find the middle element
in the sorted list.

Step 2: Compare the search element with the middle element in the sorted
list.

Step 4: If both are matching, then display "Given element found!!!"


then terminate the function.

Step 5: If both are not matching, then check whether the search element is
smaller or larger than middle element.

Step 6: If the search element is smaller than middle element, then repeat
steps 2, 3, 4 and 5 for the left sublist of the middle element.

Step 7: If the search element is larger than middle element, then repeat
steps 2, 3, 4 and 5 for the right sublist of the middle element.

Step 8: Repeat the same process until we find the search element in the list
or until sublist contains only one element.

Step 9: If that element also doesn't match with the search element, then
display "Element not found in the list!!!" and terminate the function.
Data Structures Using JAVA Semester IV

Program:

import java.util.*;

class BinarySearch {

public static void main(String args[ ])throws IOException {

int num[ ];

int key, pos, n, i;

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Enter size of array");

n=Integer.parseInt(br.readLine( ));

num=new int[n];

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

for(i=0;i<n;i++)

num[i]=Integer.parseInt(br.readLine( ));

System.out.println("Enter the element to be searched");

key=Integer.parseInt(br.readLine( ));

pos=binarySearch(num, n, key);

if(pos==-1)

System.out.println("Search is unsuccessful");

else {

System.out.println("search is successful");

System.out.println(key +" found at position "+(pos+1));

static int binarySearch(int arr[ ], n, key) {

int low, high, mid;

low=0 ;

high=n-1;

while(low<high) {
mid=(low+high)/2;
Data Structures Using JAVA Semester IV

if(arr[mid]==key)

return mid;
else {

if(key>arr[mid])

low=mid+1;

else

high=mid-1;

return -1;

OUTPUT:
Enter size of array: 5

Enter 5 elements into array:

10 20 30 40 50

Enter the element to be searched: 30

Search is successful

30 found at position 3

You might also like