0% found this document useful (0 votes)
10 views48 pages

DS Unit-4

This document covers sorting and searching algorithms, focusing on sorting techniques such as Selection Sort, Insertion Sort, and Bubble Sort. It explains the importance of sorting for optimizing data searching and presents the efficiency of these algorithms in terms of time and space complexity. Additionally, it provides examples and code implementations for each sorting method.

Uploaded by

ksuryatheja2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views48 pages

DS Unit-4

This document covers sorting and searching algorithms, focusing on sorting techniques such as Selection Sort, Insertion Sort, and Bubble Sort. It explains the importance of sorting for optimizing data searching and presents the efficiency of these algorithms in terms of time and space complexity. Additionally, it provides examples and code implementations for each sorting method.

Uploaded by

ksuryatheja2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Data Structures Unit - IV

Sorting & Searching


Sorting:
Sorting is the process of placing elements from a collection in some kind of order. Generically
the elements are arranged in either increasing (ascending) or decreasing (descending) order. E.g. A list
of words could be sorted alphabetically or by length.
A list of cities could be sorted by population, by area, or by zip code
The algorithm used for sorting is called as sorting algorithm.
Sorting algorithm specifies the way to arrange data in a particular order.
The main advantage of sorting is that data searching can be optimized to a very high level, if data
is stored in a sorted manner. Sorting is also used to represent data in more readable formats. There are
various sorting algorithms are available of them most commonly used are Bubble sort, Selection sort,
Quick sort, Insertion sort, Shell sort etc.,

Efficiency of an algorithm depends on two parameters:


1. Time Complexity:
Time Complexity is defined as the number of times a particular instruction set is executed
rather than the total time is taken. It is because the total time taken also depends on some
external factors like the compiler used, processor’s speed, etc.
2. Space Complexity:
Space Complexity is the total memory space required by the program for its execution.
Both are calculated as the function of input size(n). One important thing here is that in spite of these
parameters the efficiency of an algorithm also depends upon the nature and size of the input. Big O
Notation

It is an Asymptotic notation used to determine the relationship between the input and time. Big O
Notation expresses the run time of an algorithm in terms of how quickly it grows relative to the input ‘n’ by
defining the N number of operations that are done on it. Thus, the time complexity of an algorithm is
denoted by the combination of all O[n] assigned for each line of function.
Common types of time complexities used
• Constant time – O (1)
• Logarithmic time – O (log n)
• Linear time – O (n)
• Log liner time – O (n log n)

• Quadratic time – O (n2)

• Cubic time – O (n3)

• Exponential – O (2n)
Generally, Algorithms are analysed in three cases
• Best case
• Worst case
• Average case
Department of Computer Science, SSBN Degree College, ATP
1

Data Structures Unit - IV


Sorting techniques:
The techniques of sorting can be divided into two categories. These are:
Internal Sorting:
If all the data that is to be sorted can be adjusted at a time in the main memory, the internal
sorting method is being performed.
An in-place sorting algorithm uses constant extra space for producing the output (modifies the given array
only). It sorts the list only by modifying the order of the elements within the list.
External Sorting:
When the data that is to be sorted cannot be accommodated in the memory at the same time
and some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic tapes etc, then
external sorting methods are performed.
Selection Sort:
The selection sort algorithm sorts a list by repeatedly finding the minimum element (considering
ascending order) putting it in the first position. Then find the second minimum element in the list and put it
in the second position. This process continues till the complete list is sorted.
Example:
X is an array of integers of which the first n are to be sorted so that x[i]<=x[j]for
0<=i<j<n. X = {11 25 12 22 64}
Iteration 1 - Find the minimum element in X [0...4] and place it at beginning of X [0...4]
11 25 12 22 64
Iteration 2 - Find the minimum element in X [1...4] and place it at beginning of X [1...4]
11 12 25 22 64
Iteration 3 - Find the minimum element in X [2...4] and place it at beginning of X [2...4]
11 12 22 25 64
Iteration 4 - Find the minimum element in X [3...4] and place it at beginning of X [3...4]
11 12 22 25 64
Algorithm:
Selection Sort (A, MAX):
1. Repeat step 2 to 5 varying out from 0 to MAX-2
2. Set min = out
3. Repeat step 4 varying in from out+1 to MAX-1
4. Is A[in] < A[min] then min = in
5. Swap the value at A[out] and A[min]
6. Return.

Efficiency:
The selection sort has quadratic order (O (N2)) in best, average and worst cases. The selection
sort algorithm is suited for smaller lists and is not an efficient algorithm on larger lists.

Department of Computer Science, SSBN Degree College, ATP


2
Data Structures Unit - IV

Method:
public void selectionSort ()
{
int min;
for (int out=0; out<nElems-1; out++)
{
min=out;
for (int in=out+1; in<nElems; in++)
{
if(A[in]<A[min])
min=in;
}
swap (out, min);
}
}
public void swap(int one, int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}

Program:
//Program to illustrate Selection sort
import java.util.*;
class MyArray
{
long A []; int nElems;
public MyArray (int size)
{
A=new long[size];
nElems =0;
}
public void insert (long item)
{
A[nElems++] =item;
}
public void display ()
{
System.out.print("Array: [ ");
for (long item: A)
System.out.print(item+" ");
System.out.println("]");
}
Department of Computer Science, SSBN Degree College, ATP
3

Data Structures Unit - IV


public void swap (int one, int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}
public void selectionSort ()
{
int min;
for (int out=0; out<nElems-1; out++)
{
min=out;
for (int in=out+1; in<nElems; in++)
{
Output:
Enter how many numbers are there: 5
if(A[in]<A[min])
Enter a number: 74
min=in;
Enter a number: 15
Enter a number: 4
}
Enter a number: 65
swap (out, min);
Enter a number: 8
Before Sorting...
}
Array:[ 74 15 4 65 8 ]
After Sorting...
}
Array:[ 4 8 15 65 74 ]
}
public class SelectionSortApp
{
public static void main (String args [])
{
long item;
Scanner s=new Scanner (System.in);
System.out.println("Enter how many numbers are there:"); int
n=s.nextInt();
MyArray ARY=new MyArray(n);
for (int i=0; i<n; i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.selectionSort();
System.out.println("After Sorting...");
ARY.display();
}
}
Department of Computer Science, SSBN Degree College, ATP
4

Data Structures Unit - IV


Insertion sort:
The insertion sort algorithm virtually divides the list in to sub lists (sorted and unsorted) such that one list
contains first element and rest of the elements in another list. Since one list contains only one element
sorting is not needed. Now every element from the unsorted list is inserted at the correct position in the
sorted list. This process continues until all the elements are processed.
Let A be an array with ‘n’ elements A [1], A [2], A [3] …. A[n] is in memory. Insertion sort scans A from A [1]
to A[n], inserting each element A[k] into its proper position in the previously sorted sub array A [1], A [2],
A[k-1]. Procedure:
Pass 1: A [1] by itself is sorted
Pass 2: A [2] is inserted either before or after A [1] so that A [1], A [2] is sorted
Pass 3: A [3] is inserted into its proper place i.e., before A [1] or after A [2] or b/w A [1] and A [2] so that A
[1], A [2], A [3] are sorted.
Pass n: A[n] is inserted into its proper place in A [1], A [2], A[n-1] so that A [1], A [2], … A[n] is sorted. For
inserting A[k] in its proper place compare A[k] with A[k-1] and so on until first meeting an element A[j] such
that A[j]<A[k]. Then each of the elements A[k-1], A[k-2], A[k-3] …. A[j] is moved forward one location and
A[k] is inserted in the (j+1) th position in the array.

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands.
The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and
placed at the correct position in the sorted part.

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.
Example:

Department of Computer Science, SSBN Degree College, ATP


5
Data Structures Unit - IV

Example2:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4 (last element of the array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of
their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their
current position.
5, 6, 11, 12, 13
Algorithm:
Insertion Sort (A, MAX):
1. Repeat steps 2 to 5 varying out from 1 to MAX – 1
2. Set temp = A[out]
3. Set in = out
4. Repeat steps (a) and (b) until it becomes less than 0 or A[in] becomes less than or equal to
temp a. Shift the value at index in-1 to index in
b.Decrement in by 1
5. Store temp at index in
Method:
public void insertionSort ()
{
int out, in;
long temp;
for (out=1; out<nElems; out++)
{
temp=A[out];
in=out;
while(in>0&&A[in-1]>=temp)
{
A[in]=A[in-1];
in--;
}
A[in]=temp;
}
}

Efficiency:
The insertion sort has quadratic order (O(N2)) for average and worst cases but has linear order
(O(N)) for partially sorted lists (best case). The insertion sort is best suited for smaller lists only. It is an
efficient algorithm than bubble and selection sort when the list is nearly sorted.
Department of Computer Science, SSBN Degree College, ATP
6

Data Structures Unit - IV


Program:
//Program to illustrate Insertion sort
import java.util.*;
class MyArray
{
long A [];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}

public void insert(long item)


{
A[nElems++]=item;
}

public void display()


{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}

public void insertionSort()


{
int out,in;
long temp;
for(out=1;out<nElems;out++)
Output:
Enter how many numbers are there: 5
{
Enter a number: 74
temp=A[out];
Enter a number: 15
Enter a number: 4
in=out;
Enter a number: 65
while(in>0&&A[in-1]>=temp)
Enter a number: 8
Before Sorting...
{
Array:[ 74 15 4 65 8 ]
A[in]=A[in-1];
After Sorting...
Array:[ 4 8 15 65 74 ]
in--;
}
A[in]=temp;
}
}
}
Department of Computer Science, SSBN Degree College, ATP
7

Data Structures Unit - IV


public class InsertionSortApp
{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:");
int n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.insertionSort();
System.out.println("After Sorting...");
ARY.display();
}
}

Bubble Sorting:
Bubble sort is an Exchange sort algorithm. The basic idea of the bubble sort is to pass through the
list sequentially several times. Each pass consists of comparing each element in the file with its successor
and interchanging those two elements if they are not in proper order. The bubble sort always compares
the adjacent element and tries to place an element at its correct position.
E.g.:
X is an array of integers of which the first n are to be sorted so that x[i]<=x[j]for
0<=i<j<n. X = {25 57 48 37 12 92 86 33}
Comparisons made on the first pass:
X[0] with X[1] (25 with 57) No interchange
X[1] with X[2] (57 with 48) Interchange
X[2] with X[3] (57 with 37) Interchange
X[3] with X[4] (57 with 12) Interchange
X[4] with X[5] (57 with 92) No interchange
X[5] with X[6] (92 with 86) Interchange
X[6] with X[7] (92 with 33) Interchange
After the first pass,
X= {25 37 12 48 57 86 33 92}

Department of Computer Science, SSBN Degree College, ATP


8
Data Structures Unit - IV

The biggest element 92 in the list has found its correct position. Similarly, each iteration places an element
into its proper position.

A list of n elements requires at most n-1 passes.


The complete set of iterations can be as following:
X= {25 57 48 37 12 92 86 33}
Iteration 1 25 48 37 12 57 86 33 92
Iteration 2 25 37 12 48 57 33 86 92
Iteration 3 25 12 37 48 33 57 86 92
Iteration 4 12 25 37 33 48 57 86 92
Iteration 5 12 25 33 37 48 57 86 92
Iteration 6 12 25 33 37 48 57 86 92
Iteration 7 12 25 33 37 48 57 86 92
Algorithm:
Bubble Sort (A, MAX):
1. Repeat step 2 varying out from MAX-1 to 1
2. Repeat step 3 varying in from 0 to out-1
3. Is A[in] > A[in+1] then swap the values of A[in] and A[in+1]
4. Return.
Method:
public void bubbleSort()
{
for(int out=nElems-1;out>=1;out--)
{
for(int in=0;in<out;in++)
{
if(A[in]>A[in+1])
swap(in,in+1);
}
}
}
public void swap(int one, int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}
Efficiency:
The bubble sort has quadratic order (O(N2)) for best, worst and average cases. The bubble
sorting algorithm is suited for smaller lists and is not an efficient algorithm on larger lists.
Department of Computer Science, SSBN Degree College, ATP
9

Data Structures Unit - IV


Program:
//Program to illustrate Bubble sort
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
public void display()
{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}
public void swap(int one,int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}
public void bubbleSort()
{
for(int out=nElems-1;out>=1;out--)
{
for(int in=0;in<out;in++)
{
if(A[in]>A[in+1])
swap(in,in+1);
}
}
}
}

Department of Computer Science, SSBN Degree College, ATP


10
Data Structures Unit - IV

public class BubbleSortApp


{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:"); int
n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.bubbleSort();
System.out.println("After Sorting...");
ARY.display();
}
}

Output:
Enter how many numbers are there: 5
Enter a number: 74
Enter a number: 15
Enter a number: 4
Enter a number: 65
Enter a number: 8
Before Sorting...
Array:[ 74 15 4 65 8 ]
After Sorting...
Array:[ 4 8 15 65 74 ]
Department of Computer Science, SSBN Degree College, ATP
11

Data Structures Unit - IV


Shell sort
Insertion sort is an efficient algorithm only if the list is already partially sorted and results in an
inefficient solution in an average case. To overcome this limitation, a computer scientist, D.L. Shell
proposed an improvement over the insertion sort algorithm. The new algorithm was called shell sort. The
shell sort divides the list in to multiple sub lists basing on a time interval or gap and applies insertion sort
on those sub lists.
Features:
• Improves insertion sort by comparing the elements separated by a distance of several positions to
form multiple sub lists.

• Applies insertion sort on each sub list to move the elements towards their correct positions. •
Helps an element to take a bigger step towards its correct position, thereby reducing the number of
comparisons.

• Reduces number of comparisons.


• Faster than bubble, selection, insertion sorts but slower than quick sort.
Knuth’s Sequence:
The sequence of numbers used to generate the intervals used to divide the list in to multiple sub lists
is called the interval sequence or gap sequence. There are several approaches to generate the interval
sequence. But most often we use Knuth’s Sequence in reverse form which starts from 1 and can be
generated using the recursive expression
while(h<=nElems/3)
h=h*3+1;
The particular interval sequence is as follows

h 3*h+1 (h–1)/3
14
4 13 1
13 40 4
40 121 13
121 364 40
364 1093 121

Note: we can also generate gap sequence by considering the number of elements ‘n’ in the list and
choosing the gap as follows.

In first iteration the gap (h) = n/2 for 1st pass and decrement h by h/2 for every iteration till
h becomes 1.

Department of Computer Science, SSBN Degree College, ATP


12
Data Structures Unit - IV

Shell sort Example:

Algorithm:
1. Set h= MAX/2
2. Repeat steps 5 to 10 until h becomes less than or equal to zero.
3. Repeat steps 6 to 9 varying out from h to MAX – 1
4. Set temp = A[out]
5. Set in = out
6. Repeat steps (a) and (b) until in becomes less than h-1 or A[in-h] becomes less than or equal to
temp a) Shift the value at index in-h to index in
b) Decrement in by h (in=in-h)
7. Store temp at index in
8. Decrement h by h/2
Method 1:
public void shellSort()
{
int out, in, h=1;
long temp;
h=nElems/2;
while(h>0)
{
for(out=h; out<nElems; out++)
{
temp=A[out];
in=out;
while(in>h-1 && A[in-h]>=temp)
{
A[in]=A[in-h];
in=in-h;
}
A[in]=temp;
}
h=h/2;
}
}
Efficiency:
The Shell sort has log linear order (O(N log N)) for the best case and has O(N (log N)2)) for average
and worst cases. It is faster than bubble, selection, and insertion sorts but slower than quick sort.
Department of Computer Science, SSBN Degree College, ATP
13

Data Structures Unit - IV


Program:
//Program to illustrate Shell sort
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
public void display()
{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}
public void shellSort()
{
int out, in, h=1;
long temp;
h=nElems/2
while(h>0)
{
for(out=h; out<nElems; out++)
{
temp=A[out];
in=out;
while(in>h-1 && A[in-h]>=temp)
{
A[in]=A[in-h];
in=in-h;
}
A[in]=temp;
}
h=h/2;
}
}
}
Department of Computer Science, SSBN Degree College, ATP
14
Data Structures Unit - IV

public class ShellSortApp


{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:");
int n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.shellSort();
System.out.println("After Sorting...");
ARY.display();
}
}
Output:
Enter how many numbers are there:5
Enter a number: 74
Enter a number: 15
Enter a number: 4
Enter a number: 65
Enter a number: 8
Before Sorting...
Array:[ 74 15 4 65 8 ]
After Sorting...
Array:[ 4 8 15 65 74 ]

Quick Sort:
Quick sort was discovered by CAR Hoare in 1962. This algorithm mainly works on partition algorithm.
Partition is the underlying mechanism of quick sort. Partition means dividing the data into two groups basing
on a criteria (key value) i.e., all elements with higher key value than the specified amount are placed in one
group and the rest with lower key value than the specified amount placed in another group. This algorithm
operates by partitioning a list in to two sub lists and then calling itself recursively to quick sort each of those
sub lists.
Quick sort works in three steps
1. Partition the array into left (smaller keys) and right (bigger keys) groups.
2. Call quick sort on left group.
3. Call quick sort on right group.
Department of Computer Science, SSBN Degree College, ATP
15

Data Structures Unit - IV


Procedure:
• The algorithm chooses an element from the list called as Pivot (generally last or first element). Now the
list is partitioned based on the pivot value.

• The algorithm uses two pointers one at each end of the list.
• The pointer say, leftPtr moves from left towards right and the rightPtr moves from right towards the
left. • When the leftPtr encounters items smaller than the pivot it keeps going on because they are
already on correct side of the array. But when an element greater than pivot is found the pointer is
stopped. • Similarly, the rightPtr continues when bigger elements are found but stops when a small item
is found. • After finding the elements which are on wrong side of the arrays then those elements are
swapped. • After swapping again the pointers are continued to find the elements which are on wrong
side of array. • When the two pointers meet then the search is stopped and the pivot is restored to that
position. Now all elements left to the pivot are smaller than pivot and elements right to the pivot are
greater than pivot.

• Now the same process is continued on the two groups. This process continue until all the elements in
the list are processed.
Quick Sort Example:
Department of Computer Science, SSBN Degree College, ATP
16

Data Structures Unit - IV


Algorithm:
Quicksort (left, right):
1. If (left >= right) Return
2. Set pivot = A[right]
3. Set leftPtr = left + 1 and rightPtr = right
4. Repeat step 5 until A[leftPtr] < pivot // Search for an element greater than pivot 5. Increment leftPtr
by 1
6. Repeat step 7 until rightPtr>0 and A[rightPtr]>pivot // Search for an element smaller than pivot 7.
Decrement rightPtr by 1
8. If leftPtr>=rightPtr then Swap elements A[leftPtr] and pivot and go to step 9
Otherwise swap elements A [leftPtr] and A[rightPtr] and go to step 4
9. Quicksort (left, leftPtr– 1) // Apply quicksort on list left to pivot. 10. Quicksort (leftPtr+ 1, right)
// Apply quicksort on list right to pivot.

Method:
public void quickSort()
{
recQuickSort(0,nElems-1);
}
public void recQuickSort(int left, int right)
{
if(right-left<=0)
return;
long pivot=A[right];
int partition=partitionIt(left,right,pivot);
recQuickSort(left,partition-1);
recQuickSort(partition+1,right);

public int partitionIt (int left, int right, long pivot)


{
int leftPtr=left-1;
int rightPtr=right;
while(true)
{
while(A[++leftPtr]<pivot);
while(rightPtr>0 && A[--rightPtr]>pivot);
if(leftPtr>=rightPtr)
public void swap(int one,int two)
break;
{
else
long temp=A[one];
swap(leftPtr,rightPtr);
A[one]=A[two];
}
A[two]=temp;
swap(leftPtr,right);
}
return leftPtr;
}

Efficiency:
The quick sort has log linear order (O (N log N)) for best and average case and has quadratic order (O
(N2)) for worst case. Efficiency always depends up on the choosing the pivot element. Picking the median of
first, last and middle element of the list called as median-of-three approach is considered as the best way of
choosing the pivot.

Department of Computer Science, SSBN Degree College, ATP


17

Data Structures Unit - IV


Program:
//Program to illustrate Quick sort
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
public void display()
{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}
public void swap(int one,int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}
public int partitionIt (int left, int right, long pivot)
{
int leftPtr=left-1;
int rightPtr=right;
while(true)
{
while(A[++leftPtr]<pivot);
while(rightPtr>0 && A[--rightPtr]>pivot);
if(leftPtr>=rightPtr)
break;
else
swap(leftPtr,rightPtr);
}

swap(leftPtr,right);
return leftPtr;
}

Department of Computer Science, SSBN Degree College, ATP


18
Data Structures Unit - IV

public void recQuickSort(int left, int right)


{
if(right-left<=0)
return;
long pivot=A[right];
int partition=partitionIt(left,right,pivot);
recQuickSort(left,partition-1);
recQuickSort(partition+1,right);
}
public void quickSort()
{
recQuickSort(0,nElems-1);
}
}
public class QuickSortApp
{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:");
int n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.quickSort();
System.out.println("After Sorting...");
ARY.display();
}

}Output:
Enter how many numbers are there: 5
Enter a number: 74
Enter a number: 15
Enter a number: 4
Enter a number: 65
Enter a number: 8
Before Sorting... Array:[ 74 15 4 65 8 ]
After Sorting... Array:[ 4 8 15 65 74 ]
Department of Computer Science, SSBN Degree College, ATP
19

Data Structures Unit - IV


Heap Sort
Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios.
Heap sort algorithm is divided into two basic parts:

• Creating a Heap of the unsorted list.


• Then a sorted array is created by repeatedly removing the largest/smallest element from the heap,
and inserting it into the array. The heap is reconstructed after each removal.
Heap:
Heap is a special tree-based data structure that satisfies the following special heap properties. • Shape
Property: Heap data structure is always a Complete Binary Tree, which means all levels of the tree are
fully filled.

• Heap Property: All nodes are either [greater than or equal to] or [less than or equal to] each of its
children. If the parent nodes are greater than their children, heap is called a Max-Heap, and if the
parent nodes are smaller than their child nodes, heap is called Min-Heap.
Procedure:
The first step in heap sort is to create a Heap data structure (Max-Heap or Min-Heap). Once heap is built,
the first element of the Heap is either largest or smallest (depending upon Max-Heap or Min-Heap). That
first element of the heap is deleted and stored separately in an array. Then again heap is constructed with
the remaining elements, to again pick the first element of the heap and put it into the array. This process is
repeated until all the nodes are processed.
Algorithm:
Heap Sort (A, MAX)
The array ‘A’ of N elements can be sorted by this algorithm. First we build the heap and repeatedly delete
the root element. Since the root always contains the largest node, it deletes the elements in decending
order, Heap (A,N)
1. Repeat for j=1 to n-1 Call insertHeap(A,J,A[J+1])
2. Repeat while N>1Call deleteHeap(A, N, Item)
3. Set A (N+1)=Item
4. Exit
Inserting into a Heap:
Let H is a heap with N elements, and let us suppose that an ‘item’ of information is given, we insert item
into the heap H as follows.
1. First join ‘Item’ at the end of H so that H is still a complete tree, but not necessarily a
heap. 2. Then let Item rise to its suitable place in H so that H is finally a heap
Insertheap(Tree, N, Item)
1. Set N=N+1 & ptr=N
2. Repeat steps 3 to 6 while ptr<1
3. Set par=ptr/2
4. If item<Tree[par]
5. Set Tree[par]=Item & return Set Tree[ptr]=tree[par]
6. Set ptr=par
7. Tree[1]=Item
8. Return

Department of Computer Science, SSBN Degree College, ATP


20
Data Structures Unit - IV

Deleting the root of a Heap:


Let us suppose H is a heap with N elements, and to delete the root R of H, the
process is 1. Assign the root R to some variable item
2. Replace the deleted node R by the last node so that it is still a complete tree but not a
heap 3. Adjust the tree such that H is again a heap
Deleteheap(tree, N, Item)
1. Set Item=tree[1] and Set Last=tree[N]
2. N=N-1
3. Set ptr=1, left=2 & right=3
4. Repeat steps 5 to 7 while right <=N
5. If last >=tree[left] and last >=Tree[Right] then Tree[ptr]=last & return
6. If tree[right] <=tree[left] then
Set tree[ptr]=tree[left]
Ptr=left
else
Set tree[ptr]=tree[right]
Ptr=right
7. Set left=2*ptr & right=left 1
8. If left=N and it last<tree[left]
9. Set ptr=left
10. Set tree[ptr]=last
11. Return
Efficiency:
Heap sort has log linear order of growth (O(N log N)) for best, average and worst
cases. Program:
//Program to illustrate Heap sort
//ProjectName:- HeapSortApp ClassName:-HeapSortApp
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
Department of Computer Science, SSBN Degree College, ATP
21

Data Structures Unit - IV


public void heapSort()
{
// Build heap (rearrange array)
for (int i = nElems / 2 - 1; i >= 0; i--)
heapify(A, nElems, i);
// One by one extract an element from heap
for (int i = nElems - 1; i > 0; i--)
{
// Move current root to end
swap(0,i);
// call max heapify on the reduced heap
heapify(A, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(long arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(i,largest);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public void display()
{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}
Department of Computer Science, SSBN Degree College, ATP
22
Data Structures Unit - IV

public void swap(int one,int two)


{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}
}
public class HeapSortApp
{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:"); int
n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Before Sorting...");
ARY.display();
ARY.heapSort();
System.out.println("After Sorting...");
ARY.display();
}
}

Output:
Enter how many numbers are there: 5
Enter a number: 74
Enter a number: 15
Enter a number: 4
Enter a number: 65
Enter a number: 8
Before Sorting... Array:[ 74 15 4 65 8 ]
After Sorting... Array:[ 4 8 15 65 74 ]
Department of Computer Science, SSBN Degree College, ATP
23

Data Structures Unit - IV


Searching:
Finding for a particular element in a given list is termed as searching. Searching is used in most of
the applications.
E.g. Searching for a contact in a telephone directory
Searching for a book in library
The algorithm used for searching is called as searching algorithm. There are various searching algorithms
are available of them most commonly used are
Linear search, Binary search etc.,
Basic Terms:
File/ Table:
A file or a table is a sequence of n elements which need to be sorted or where an element is
searched. E.g., Telephone directory can be considered as a File where contacts need to be sorted
alphabetically or a contact can be searched from the directory.
Record: Every element in the file or table is called as a Record.
Key: A record in the file or table is always identified by a value called as Key. Keys can be of two types
Internal or Embedded Key:
If the key is contained within the record then the key is called as Internal or Embedded
key. External Key:
If the key is present external to the record then the key is called as External key.
Some keys are having unique values such keys are called as Primary Key and some of them contain
duplicate values those are called as Secondary keys.
Linear Search:
A linear search is the basic and simple search algorithm. A linear search searches an element or value from
an array till the desired element or value is not found and it searches in a sequence order. It compares the
element with all the other elements given in the list and if the element is matched it returns the value index
else it returns -1. Linear Search is applied on the unsorted or unordered list when there are fewer elements
in a list.
Algorithm:
Linear Search (A, Max, key):
1. Repeat steps varying i from 0 to MAX-1
2. Is A[i]=key then return i
3. Return -1
Method:
public int linearSearch(long key)
{
for (int i=0; i<nElems;i++)
{
if(A[i]==key)
return i;
}
return -1;
}
Department of Computer Science, SSBN Degree College, ATP
24

Data Structures Unit - IV


Efficiency:
Linear search has linear order (O (N)) for worst case and average case and has constant time (O (1))
for best case. Linear search is best suited for smaller lists but linear search is an expensive algorithm for
larger lists.
Program:
//Program to illustrate Linear Search
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
public void display()
{
System.out.print("Array:[ ");
for (long item: A)
System.out.print(item+" ");
System.out.println("]");
}
public int linearSearch(long key)
{
for(int i=0;i<nElems;i++)
{
if(A[i]==key)
return i;
}
return -1;
}
}

Department of Computer Science, SSBN Degree College, ATP


25
Data Structures Unit - IV

public class LinearSearchApp


{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:");
int n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
System.out.println("Elements in the array...");
ARY.display();
System.out.println("Enter an element to search in the
Array:"); item =s.nextLong();
int pos=ARY.linearSearch(item);
if(pos==-1)
System.out.println("Element not found");
else
System.out.println("Element is fount at position
:"+(pos+1)); }
}

Output:
Enter how many numbers are there: 5
Enter a number: 74
Enter a number: 45
Enter a number: 63
Enter a number: 15
Enter a number: 2
Elements in the array...
Array: [ 74 45 63 15 2 ]
Enter an element to search in the
Array: 63
Element is found at position: 3
Department of Computer Science, SSBN Degree College, ATP
26

Data Structures Unit - IV


Binary Search:
Binary Search is an efficient algorithm to find an item from an ordered list of items which works on
divide & conquer strategy. It works by repeatedly dividing the list in to half portion that could contain
element. It starts by examining the middle item of the list. If the value is matched then the search is
stopped. If the value is less than the middle element, then it must lie in the lower half of the array and if
it's greater than the element then it must lie in the upper half of the array. This process is repeated on the
lower (or upper) half of the array. Binary Search is useful when there are large numbers of elements in an
array. Algorithm:
Binary Search(A, Max, key):
1. Set lower =0 and upper = MAX-1
2. Repeat steps from 3 to 6 until lower is less than or equal to upper
3. Set pos=(lower+upper)/2
4. If A[pos]==key then return pos
5. If A[pos]<key then lower =pos+1
6. If A[pos]>key then upper =pos-1
7. Return -1

Method:
public int binarySearch(long key)
{
int lower=0;
int upper=nElems-1;
while(true)
{
int pos=(lower+upper)/2;
if(A[pos]==key)
return (pos);
else if(lower>upper)
return -1;
else
{
if(A[pos]<key)
lower=pos+1;
else
upper=pos-1;
}
}
}

Department of Computer Science, SSBN Degree College, ATP


27
Data Structures Unit - IV

Example:

Efficiency:
Binary search has log linear order (O (N log N)) for worst case, logarithmic order (O (log N)) of average
case and has constant time (O (1)) for best case. Even though binary search is better than linear search but
it’s also important to note that for smaller values of N additional cost of sorting is probably not worth it.
Sometimes sorting larger list can be so expensive that linear search is best choice.
Program:
//Program to illustrate Binary Search
import java.util.*;
class MyArray
{
long A[];
int nElems;
public MyArray(int size)
{
A=new long[size];
nElems =0;
}
public void insert(long item)
{
A[nElems++]=item;
}
public void display()
{
System.out.print("Array:[ ");
for(long item: A)
System.out.print(item+" ");
System.out.println("]");
}
Department of Computer Science, SSBN Degree College, ATP
28

Data Structures Unit - IV


public int binarySearch(long key)
{
int lower=0;
int upper=nElems-1;
while(true)
{
int pos=(lower+upper)/2;
if(A[pos]==key)
return (pos);
else if(lower>upper)
return -1;
else
{
if(A[pos]<key)
lower=pos+1;
else
upper=pos-1;
}
}
}
public void swap(int one,int two)
{
long temp=A[one];
A[one]=A[two];
A[two]=temp;
}

public void sort()


{
for(int out=nElems-1;out>=1;out--)
{
for(int in=0;in<out;in++)
{
if(A[in]>A[in+1])
swap(in,in+1);
}
}
}
}

Department of Computer Science, SSBN Degree College, ATP


29
Data Structures Unit - IV

public class BinarySearchApp


{
public static void main(String args[])
{
long item;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers are there:");
int n=s.nextInt();
MyArray ARY=new MyArray(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
item=s.nextLong();
ARY.insert(item);
}
ARY.sort();
System.out.println("Elements in the array...");
ARY.display();
System.out.println("Enter an element to search in the
Array:"); item =s.nextLong();
int pos=ARY.binarySearch(item);
if(pos==-1)
System.out.println("Element not found");
else
System.out.println("Element is fount at position
:"+(pos+1)); }
}

Output:
Enter how many numbers are there: 5
Enter a number: 74
Enter a number: 12
Enter a number: 56
Enter a number: 85
Enter a number: 2
Elements in the array...
Array:[ 2 12 56 74 85 ]
Enter an element to search in the Array: 56
Element is fount at position :3
Department of Computer Science, SSBN Degree College, ATP
30

You might also like