Professional Documents
Culture Documents
Unit - V: Sorting and Searching
Unit - V: Sorting and Searching
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.
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.
Program:
import java.io.*;
int i, size;
int array[ ];
for(i=0;i<size;i++) {
array[i] = Integer.parseInt(in.readLine());
System.out.println( );
selection_srt(array, array.length);
System.out.print(array[i]+" ");
System.out.println( );
int index_of_min = x;
if(array[index_of_min]>array[y])
index_of_min = y;
} }
array[x] = array[index_of_min];
array[index_of_min] = temp;
Output:
Enter 1 number: 9
Enter 2 number: 5
Enter 3 number: 1
Enter 4 number: 10
Enter 5 number: 2
Selection Sort
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:
import java.io.*;
int i,size;
int array[ ];
for(i=0;i<size;i++) {
System.out.println( );
bubble_srt(array, array.length);
System.out.print(array[i]+" ");
System.out.println( );
int i, j,t=0;
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
import java.io.*;
int i,size;
int array[ ];
size = Integer.parseInt(in.readLine());
for(i=0;i<size;i++) {
System.out.println();
insertion_srt(array, array.length);
System.out.print(array[i]+" ");
System.out.println( );
int j = i;
int B = array[i];
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:
import java.io.*;
int i,size;
int array[ ];
for(i=0;i<size;i++) {
array[i] = Integer.parseInt(in.readLine());
System.out.println( );
quick_srt(array, 0, array.length-1);
System.out.print(array[i]+" ");
System.out.println();
int lo = low;
int hi = n;
if (lo >= n) {
return;
lo++;
hi--;
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}}
int T = hi;
hi = lo;
lo = T;
}
Data Structures Using JAVA Semester IV
HEAP SORT:
A heap is a complete binary tree which is represented using array or
sequential representation.
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.
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.
Program:
import java.util.*;
int mid;
if(mid+high)/2;
mergeSort(low, mid);
mergeSort(mid+1,high);
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];
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);
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.
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 {
int num[ ];
int key,pos,n,i;
n=Integer.parseInt(br.readLine( ));
num=new int[n];
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");
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
10 20 30 40 50
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.
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 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 {
int num[ ];
n=Integer.parseInt(br.readLine( ));
num=new int[n];
for(i=0;i<n;i++)
num[i]=Integer.parseInt(br.readLine( ));
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");
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
10 20 30 40 50
Search is successful
30 found at position 3