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

Data Structures Notes

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

Data Structures Notes

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

72

B.Sc. IV SEMESTER

Explain in detail about sorting and different types of sorting techniques

Sorting is a technique to rearrange the elements of a list in ascending or


descending order, which can be numerical, or any user-defined order. Sorting
can be classified in two types;
Internal Sorts
This method uses only the primary memory during sorting process. All data
items are held in main memory and no secondary memory is required this
sorting process. If all the data that is to be sorted can be accommodated at a
time in memory is called internal sorting. There is a limitation for internal
sorts; they can only process relatively small lists due to memory constraints.
There are 3 types of internal sorts.

SELECTION SORT :- Ex:- Selection sort algorithm, Heap Sort algorithm

INSERTION SORT :- Ex:- Insertion sort algorithm, Shell Sort algorithm

EXCHANGE SORT :- Ex:- Bubble Sort Algorithm, Quick sort algorithm

External Sorts

Sorting large amount of data requires external or secondary memory. This


process uses external memory such as HDD, to store the data which is not fit
into the main memory. So, primary memory holds the currently being sorted
data only. All external sorts are based on process of merging. Different parts of
data are sorted separately and merged together.

Ex:- Merge Sort

Explain the algorithm for selection sort and give a suitable example.
In selection sort the list is divided into two sub-lists sorted and unsorted.
These two lists are divided by imaginary wall. We find a smallest element from
unsorted sub-list and swap it to the beginning. And the wall moves one
element ahead, as the sorted list is increases and unsorted list is decreases.

Assume that we have a list on ―n‖ elements. By applying selection sort, the first
element is compared with all remaining (n-1) elements. The smallest element is
placed at the first location. Again, the second element is compared with
remaining (n-1) elements. At the time of comparison, the smaller element is
swapped with larger element. Similarly, entire array is checked for smallest
element and then swapping is done accordingly. Here we need n-1 passes or
iterations to completely rearrange the data.

Data Structures Prepared by Mahesh MCA


73
B.Sc. IV SEMESTER

Algorithm:
The idea of algorithm is quite simple. Array is imaginary divided into two parts
- sorted one and unsorted one. At the beginning, sorted part is empty, while
unsorted one contains whole array. At every step, algorithm finds minimal
element in the unsorted part and adds it to the end of the sorted one. When
unsorted part becomes empty, algorithm stops.

When algorithm sorts an array, it swaps first element of unsorted part with
minimal element and then it is included to the sorted part.

Selection_Sort ( A [ ] , N )
Step 1 : Repeat For K = 0 to N – 2 Begin
Step 2 : Set POS = K
Step 3 : Repeat for J = K + 1 to N – 1 Begin
If A[ J ] < A [ POS ]
Set POS = J
End For
Step 4 : Swap A [ K ] with A [ POS ]
End For
Step 5 : Exit
A list of unsorted elements are: 23 78 45 8 32 56

A list of sorted elements now : 8 23 32 45 56 78

Data Structures Prepared by Mahesh MCA


74
B.Sc. IV SEMESTER

Example

public class SelectionSort


{
public static void main(String a[])
{
int[] arr = {9,14,3,2,43,11,58,22};
int index,i,j;
System.out.println("List Before Sorting ");
for(int x:arr){
System.out.print(x+" ");
}
System.out.println();
for (i = 0; i < arr.length - 1; i++)
{
index = i; for (j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j; //searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
System.out.println("After Selection Sort");
for(int x:arr){
System.out.print(x+" ");
}
}
}

Data Structures Prepared by Mahesh MCA


75
B.Sc. IV SEMESTER

Explain the algorithm for insertion sort and give a suitable example.

Both the selection and bubble sorts exchange elements. But insertion sort does
not exchange elements. In insertion sort the element is inserted at an
appropriate place similar to card insertion. Here the list is divided into two
parts sorted and unsorted sub-lists. In each pass, the first element of unsorted
sub list is picked up and moved into the sorted sub list by inserting it in
suitable position. Suppose we have „n‟ elements, we need n-1 passes to sort
the elements.

Insertion sort works this way:

It works the way you might sort a hand of playing cards:

We start with an empty left hand [sorted array] and the cards face down
on the table [unsorted array].
Then remove one card [key] at a time from the table [unsorted array], and
insert it into the correct position in the left hand [sorted array].
To find the correct position for the card, we compare it with each of the
cards already in the hand, from right to left.

Advantages of Insertion Sort:


It is very simple.
It is very efficient for small data sets.
It is stable; i.e., it does not change the relative order of elements with
equal keys.
In-place; i.e., only requires a constant amount O(1) of additional memory
space.
Algorithm
INSERTION_SORT (A)

1. FOR j ← 2 TO length[A]
2. DO key ← A[j]
3. {Put A[j] into the sorted sequence A[1 . . j − 1]}
4. i ← j − 1
5. WHILE i > 0 and A[i] > key
6. DO A[i +1] ← A[i]
7. i ← i – 1
8. A[i + 1] ← key

Data Structures Prepared by Mahesh MCA


76
B.Sc. IV SEMESTER

A list of unsorted elements are: 78 23 45 8 32 36 . The results of insertion


sort for each pass is as follows:-

A list of sorted elements now : 8 23 32 36 45 78

Example:

public class InsertionSort {


public static void main(String a[]){
int[] arr = {9,14,3,2,43,11,58,22};
int n,key,j,i ;
System.out.println("List Before Sorting");
for(int x:arr){
System.out.print(x+" "); }
System.out.println();
n = arr.length;
for ( j = 1; j < n; j++) {
key = arr[j];
i = j-1;
while ( (i > -1) && ( arr [i] > key ) ) {
arr [i+1] = arr [i];
i--;
}
arr[i+1] = key;
}
System.out.println("List After Sorting");

Data Structures Prepared by Mahesh MCA


77
B.Sc. IV SEMESTER

for(int x:arr){
System.out.print(x+" "); }
}
}

Explain the algorithm for bubble sort and give a suitable example.
In bubble sort method the list is divided into two sub-lists sorted and unsorted.
The smallest element is bubbled from unsorted sub-list. After moving the
smallest element the imaginary wall moves one element ahead. The bubble sort
was originally written to bubble up the highest element in the list. But there is
no difference whether highest / lowest element is bubbled. This method is easy
to understand but time consuming. In this type, two successive elements are
compared and swapping is done. Thus, step-by-step entire array elements are
checked. Given a list of „n‟ elements the bubble sort requires up to n-1 passes
to sort the data.

Algorithm for Bubble Sort:

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.

Bubble_Sort ( A [ ] , N )

Step 1 : Repeat For P = 1 to N – 1 Begin

Step 2 : Repeat For J = 1 to N – P Begin

Step 3 : If ( A [ J ] < A [ J – 1 ] )

Swap ( A [ J ] , A [ J – 1 ] )

End For End For

Step 4 : Exit

Data Structures Prepared by Mahesh MCA


78
B.Sc. IV SEMESTER

A list of unsorted elements are: 10 47 12 54 19 23

(Bubble up for highest value shown here)

Example

public class BubbleSort { public static void main(String[ ] args) {

int arr[ ] ={3,60,35,2,45,320,5};

int n , temp ,i , j;

System.out.println("Array Before Bubble Sort");

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

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

System.out.println( );

n = arr.length; temp = 0;

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

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

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

//swap elements

Data Structures Prepared by Mahesh MCA


79
B.Sc. IV SEMESTER

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

System.out.println("Array After Bubble Sort");

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

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

Explain the algorithm for QUICK sort ( partition exchange sort) and give a
suitable example.
Quick sort is based on partition. It is also known as partition exchange sorting.
It was invented by CAR Hoare. The basic concept of quick sort process is pick
one element from an array and rearranges the remaining elements around it.
This element divides the main list into two sub lists. This chosen element is
called pivot. Once pivot is chosen, then it shifts all the elements less than pivot
to left of value pivot and all the elements greater than pivot are shifted to the
right side. This procedure of choosing pivot and partition the list is applied
recursively until sub-lists consisting of only one element.

Ex:- A list of unsorted elements are: 8 3 2 11 5 14 0 2 9 4 20

Data Structures Prepared by Mahesh MCA


80
B.Sc. IV SEMESTER

Algorithm for quick sort:


quicksort(q)

varlist less, pivotList, greater

if length(q) ≤ 1

return q

select a pivot value pivot from q

for each x in q except the pivot element

if x < pivot then add x to less

if x ≥ pivot then add x to greater

add pivot to pivotList

return concatenate(quicksort(less), pivotList, quicksort(greater))

Time Complexity of Quick sort:


Best case : O (n log n)

Average case : O (n log n)

Data Structures Prepared by Mahesh MCA


81
B.Sc. IV SEMESTER

Worst case : O (n2)

Advantages of quick sort


This is faster sorting method among all.
Its efficiency is also relatively good.
It requires relatively small amount of memory.
Disadvantages of quick sort:
It is complex method of sorting so, it is little hard to implement than other
sorting methods.
Example:
public class MyQuickSort {
private int array[ ];
private int length; public void sort (int[ ] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length; quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j) {
while (array[i] < pivot) { i++;
}
while (array[j] > pivot) { j--;
}
if (i <= j) {
exchangeNumbers(i, j);
i++;
j--;
}
}
if (lowerIndex < j)
quickSort(lowerIndex, j); if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];

Data Structures Prepared by Mahesh MCA


82
B.Sc. IV SEMESTER

array[i] = array[j];
array[j] = temp;
}
public static void main(String a[ ]){
MyQuickSort sorter = new MyQuickSort();
int[] arr = {24,2,45,20,56,75,2,56,99,53,12};
System.out.println("List before sort ");
for(int x :arr)
System.out.print(x+" ");
sorter.sort(arr);
System.out.println("\nList after sort");
for(int x:arr){
System.out.print(x+ " ");
System.out.print(" ");
}
}
}

Explain the algorithm for Merge sort and give a suitable example.
The basic concept of merge sort is divides the list into two smaller sub-lists of
approximately equal size. Recursively repeat this procedure till only one
element is left in the sub-list. After this, various sorted sub-lists are merged to
form sorted parent list. This process goes on recursively till the original sorted
list arrived.

Algorithm for merge sort:


Merge sort is based on the divide-and-conquer paradigm. Its worst-case
running time has a lower order of growth than insertion sort. Since we are
dealing with sub-problems, we state each sub-problem as sorting a sub-array
A[p .. r]. Initially, p = 1 and r = n, but these values change as we recurse
through sub-problems.

To sort A[p .. r]:

1. Divide Step

If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p .. r] into two sub-arrays A[p .. q] and A[q + 1 .. r], each

Data Structures Prepared by Mahesh MCA


83
B.Sc. IV SEMESTER

containing about half of the elements of A[p .. r]. That is, q is the halfway point
of A[p .. r].

2. Conquer Step

Conquer by recursively sorting the two sub-arrays A[p .. q] and A[q + 1 .. r].

3. Combine Step

Combine the elements back in A[p .. r] by merging the two sorted sub-arrays
A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we
will define a procedure MERGE (A, p, q, r).

Note that the recursion bottoms out when the sub-array has just one element,
so that it is sorted. To sort the entire sequence A[1 .. n], make the initial call to
the procedure MERGE-SORT (A, 1, n).

Properties
It is a Stable algorithm i.e does not change the relative order of elements
with equal keys
It does not require random access to data

Data Structures Prepared by Mahesh MCA


84
B.Sc. IV SEMESTER

Time Complexity of merge sort:


Best case : O (n log n)

Average case : O (n log n)

Worst case : O (n log n)

Example:

public class MyMergeSort {

private int[ ] array;

private int[ ] tempMergArr;

private int length;

public static void main(String a[ ]){

int[ ] inputArr = {45,23,11,89,77,98,4,28,65,43};

MyMergeSort mms = new MyMergeSort( );

System.out.println("Before sorting ");

for(int i:inputArr)

System.out.print(i +" ");

mms.sort(inputArr);

System.out.println("\nAfter sorting ");

for(int i:inputArr)

System.out.print(i +" ");

public void sort(int inputArr[ ]) {

this.array = inputArr;

this.length = inputArr.length;

this.tempMergArr = new int[length];

doMergeSort(0, length - 1);

Data Structures Prepared by Mahesh MCA


85
B.Sc. IV SEMESTER

private void doMergeSort(int lowerIndex, int higherIndex) {

if (lowerIndex < higherIndex) {

int middle = lowerIndex + (higherIndex - lowerIndex) / 2;

// Below step sorts the left side of the array

doMergeSort(lowerIndex, middle);

// Below step sorts the right side of the array

doMergeSort(middle + 1, higherIndex);

// Now merge both sides

mergeParts(lowerIndex, middle, higherIndex);

private void mergeParts(int lowerIndex, int middle, int higherIndex) {

for (int i = lowerIndex; i <= higherIndex; i++) {

tempMergArr[i] = array[i];

int i = lowerIndex;

int j = middle + 1;

int k = lowerIndex;

while (i <= middle && j <= higherIndex) {

if (tempMergArr[i] <= tempMergArr[j]) {

array[k] = tempMergArr[i];

i++;

else {

Data Structures Prepared by Mahesh MCA


86
B.Sc. IV SEMESTER

array[k] = tempMergArr[j];

j++;

k++;

while (i <= middle) {

array[k] = tempMergArr[i];

k++;

i++;

Write a short notes on SEARCHING


Searching refers to the operation of finding the location of a given item in list of
items. Consider an array is given with ‗n‘ elements. A specific element ‗item‘ is
given to search. Now, we want to find whether the item is available in the list
of n elements or not. If the search item is exist, then it refers to successful
search; otherwise, it refers to unsuccessful search.

Most important techniques used for search operation are:

1. Linear search
2. Binary search
1. LINEAR SEARCH
Consider an array K with n elements as K[1], K[2], . . . K[n]. Suppose an item
of information is given to search.

Data Structures Prepared by Mahesh MCA


87
B.Sc. IV SEMESTER

In this technique, compare item value with each element of K form index 1 to
index n. At any position i, if K[i]=item, then return index i value refers to
successful search; otherwise, return -1 refers to unsuccessful search.

Example: Search an element 19 from the list of elements: 18 35 78 23


19 709

item = 19

i=1 K[1]=item → 18 = 19 FALSE

i=2 K[2]=item → 35 = 19 FALSE

i=3 K[3]=item → 78 = 19 FALSE

i=4 K[4]=item → 23 = 19 FALSE

i=5 K[5]=item → 19 = 19 TRUE

ELEMENT FOUND

Algorithm NonRecLSearch(K, n, item):


Suppose K is an array that contains ‗n‘ elements. Search element is given in
the variable ‗item‘.

This function returns an index position ‗i' if the element is found; otherwise,
return -1.

Step 1: Repeat for i ← 1 to n


If K[i]=item Then
Return i
EndIf
EndRepeat
Step 2: Return -1
Algorithm RecLSearch(K, n,item):
Step 1: If n = 0 Then
Return -1
ElseIf K[n]=item Then
Return n
Else
Return RecLSearch(K, n-1, item)
EndIf

Data Structures Prepared by Mahesh MCA


88
B.Sc. IV SEMESTER

// PROGRAM TO SEARCH A GIVEN ELEMENT USING LINEAR SEARCH

public class LinearSearchExample


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

Time Complexity:

The worst-case and average-case time complexity of linear search is O(n).

2. Binary Search :
Binary search is another searching algorithm, that takes less time complexity
compared with the linear search. Binary search can be applied only on the
array which is available in sorted order.

Consider K is an with n elements as K[1]≤K[2]≤. . . . ≤K[n]. Suppose an item of


information is given to search in the variable ITEM.
In binary search technique, first compute
Mid = (Low+High) / 2
Where, Low refers to the first index and High refers to last index of the array in
the initial call. Now, the process falls into any one of the following three cases.

Case 1: If ITEM = K[Mid]; Then the search is successful search.

Data Structures Prepared by Mahesh MCA


89
B.Sc. IV SEMESTER

Case 2: If ITEM > K[Mid]; Then the ITEM can appear only in the right half
of the array. So, we reset the Low value as Low = Mid+1 and begin
search again.

Case 3: If ITEM < K[Mid]; Then the ITEM can appear only in the left half of
the array. So, we reset the High value as High = Mid-1 and begin
search again.

This procedure is repeated upto we reach Low > High. When we obtain this
condition, it indicates that the search is unsuccessful search.

Example 1: Search an element 44 from the list


11 22 30 33 41 44 55

Low = 1 High = 7 Mid = (1+7) / 2 = 4


ITEM = K[Mid] 44 = 33 FALSE
ITEM > K[Mid] 44 > 33 TRUE
Reset Low = 4+1 = 5

Low = 5 High = 7 Mid = (5+7)/2 = 6


ITEM = K[Mid] 44 = 44 TRUE

SUCCESSFUL SEARCH, ITEM FOUND

Algorithm Non-Recursive BSearch(K, Low, High, ITEM):


Consider K is a sorted array and ITEM of information is given to search. Low,
High and Mid variables refers to beginning, ending and middle locations of the
given array K.
This function is used to find the location of the search ITEM and returns index
value if found; otherwise, it return -1.

Step 1: Repeat while Low ≤ High


Mid ← (Low+High)/2
If ITEM < K[Mid] Then
High ← Mid-1
ElseIf ITEM > K[Mid] Then
Low ← Mid+1
Else
Return Mid
EndIf
EndRepeat
Step 2: Return -1

Data Structures Prepared by Mahesh MCA


90
B.Sc. IV SEMESTER

Algorithm Recursive BSearch(K, Low, High, ITEM):

Step 1: If Low ≤ High Then


Mid ← (Low+High)/2
If ITEM = K[Mid] Then
Return Mid
ElseIf ITEM < K[Mid] Then
Return RBsearch(K, Low, Mid-1, ITEM)
Else
Return RBsearch(K,Mid+1,High,ITEM)
EndIf
EndIf
Step 2: Return -1

Java program for implementation of Binary Search

class BinarySearchExample
{
public static void binarySearch(int arr[ ], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if (arr[mid] == key)
{
System.out.println("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");

Data Structures Prepared by Mahesh MCA


91
B.Sc. IV SEMESTER

}
}
public static void main(String args[ ])
{
int arr[ ] = {10,20,30,40,50};
int key = 40;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

Data Structures Prepared by Mahesh MCA


92
B.Sc. IV SEMESTER

DATA STRUCTURES USING JAVA LAB


/*1.Write a Program to implement the Linked List operations?*/
import java.util.*;
public class LinkedListDemo
{
public static void main(String args[])
{
LinkedList ll = new LinkedList();// Here ll is a object to LinkedList class
ll.add("Virat");
ll.add("Dhoni");
ll.add("Rahane");
ll.add("Jadeja");
ll.add("Vijay");
System.out.println("Linked List Content: \n" +ll);
ll.addFirst("Ashwin");
ll.addLast("Zaheer");
System.out.println("LinkedList Content after addition: \n" +ll);

ll.removeFirst();
ll.removeLast();
System.out.println("LinkedList after deletion of first and last element: \n" +ll);
ll.add(1, "Karan");
ll.remove(2);
System.out.println("Final Content: \n" +ll);
}
}

Save this program with LinkedList.java.


At command prompt:
D:\JDS Programs>javac -Xlint LinkedListDemo.java
D:\JDS Programs>java LinkedListDemo
OUTPUT:
Linked List Content:
[Virat, Dhoni, Rahane, Jadeja, Vijay]
LinkedList Content after addition:
[Ashwin, Virat, Dhoni, Rahane, Jadeja, Vijay, Zaheer]
LinkedList after deletion of first and last element:
[Virat, Dhoni, Rahane, Jadeja, Vijay]
Final Content:
[Virat, Karan, Rahane, Jadeja, Vijay]

Data Structures Prepared by Mahesh MCA


93
B.Sc. IV SEMESTER

//2) Write a Program to implement the Stack operations using an Array?


import java.util.*;
import java.io.*;
class MyStack
{
private int top;
private int item[ ];

MyStack(int size)
{
top = -1;
item = new int[size];
}

void pushItem(int data)


{
if (top == item.length - 1)
{
System.out.println("Stack is Full");
}
else
{
item[++top] = data;
System.out.println("Pushed Item :" + item[top]);
}
}

void popItem( )
{
if (top < 0)
{
System.out.println("Stack is Empty");
}
else
{
top--;
System.out.println("Pop Item : " + item[top+1]);
}
}

public void display( )


{
for(int i =top; i>=0;i--)
System.out.println(item[i]);
}

Data Structures Prepared by Mahesh MCA


94
B.Sc. IV SEMESTER

}
class StackExample
{
public static void main(String[] args) throws IOException
{
MyStack stk = new MyStack(10);
boolean yes=true;
int choice;
Scanner sc = new Scanner(System.in);
//BufferedReader is = new BufferedReader(new InputStreamReader(System.in));

do{
System.out.println("_________________");
System.out.println("Menu:");
System.out.println("_________________");
System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit\n\nEnter Choice");
choice = sc.nextInt();
switch(choice)
{
case 1: System.out.println("Enter Push Item: ");
stk.pushItem(sc.nextInt());
break;
case 2: stk.popItem( );break;
case 3: System.out.println("Stack elements:");
stk.display( ); break;
case 4: yes = false;break;
default: System.out.println("Invalid Choice");
}
}while(yes==true);
}
}

Save this program with StackExample.java.


At command prompt:
D:\JDS Programs>javac StackExample.java
D:\JDS Programs>java StackExample
Output:
___________________

Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
1
Enter Push Item :
77
Pushed Item : 77

Data Structures Prepared by Mahesh MCA


95
B.Sc. IV SEMESTER

___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
1
Enter Push Item :
66
Pushed Item : 66
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
3
Stack element
66 77
77
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
2
Pop item:66

___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
4

//3.Write a Program to implement the Queue operations using an array?


class MyQueue
{
int front;
int item[ ];
int rear;
int temp;
MyQueue(int size)
{

Data Structures Prepared by Mahesh MCA


96
B.Sc. IV SEMESTER

front=-1;
rear=-1;
item=new int[size];
}
void eQ(int data)
{
if (rear==item.length-1)
{
System.out.println("Queue is full");
}
else
{
if (rear==-1)
{
front = 0;
rear = 0;
item[rear] = data;
}
else if (rear+1<item.length)
item[++rear] = data;
System.out.println("Element " + data + " is entered into the Queue ");
display();
}
}
public void dQ( )
{
if(front<0)
{
System.out.println("Queue is Empty");
}
else
{
temp=front;
front++;
System.out.println("Deleted element from the queue is:"+item[temp]);
display( );
}
}
public void display( )
{
if(rear >= front)
{
System.out.println("Elements in the Queue :");
for(int i=front;i<=rear;i++)
{
System.out.println(item[i]);

Data Structures Prepared by Mahesh MCA


97
B.Sc. IV SEMESTER

}
}
}

public static void main(String[ ] args)


{
MyQueue q=new MyQueue(5);
q.eQ(5);
q.eQ(10);
q.eQ(15);
q.eQ(22);
q.dQ();
q.dQ();
q.eQ(30);

}
}

Save this program with MyQueue.java.


At command prompt:
D:\ JDS Programs>javac MyQueue.java
D:\JDS Programs>java MyQueue
Output:
Element 5 is entered into the Queue
Elements in the Queue :
5
Element 10 is entered into the Queue
Elements in the Queue :
5
10
Element 15 is entered into the Queue
Elements in the Queue :
5
10
15
Element 22 is entered into the Queue
Elements in the Queue :
5
10
15
22
Deleted element from the queue is:5
Elements in the Queue :
10
15
22
Deleted element from the queue is:10
Elements in the Queue :
15
22
Element 30 is entered into the Queue
Elements in the Queue :
15
22
30

Data Structures Prepared by Mahesh MCA


98
B.Sc. IV SEMESTER

//4.Write Programs to implement the Stack operations using a single linked list

import java.io.*;
class MyNode
{
int item;
MyNode next;
MyNode(int val)
{
item = val;
}
public void displayNode()
{
System.out.println(item );
}
}

class MyLinkedList
{
MyNode first;
boolean isEmpty()
{
return (first==null);
}
void insert(int val)
{
MyNode newNode = new MyNode(val);
newNode.next = first;
first = newNode;
}
MyNode delete()
{
MyNode temp = first;
first = first.next;
return temp;
}
void display()
{
System.out.println("Elements from top to bottom");
MyNode current = first;
while(current != null)
{
current.displayNode();
current = current.next;
}
System.out.println("");
}

Data Structures Prepared by Mahesh MCA


99
B.Sc. IV SEMESTER

class MyStack
{
MyLinkedList list;
MyStack()
{
list = new MyLinkedList();
}
void push(int num)
{
list.insert(num);
}
MyNode pop()
{
return list.delete();
}
boolean isEmpty()
{
return list.isEmpty();
}
void displayStack()
{
System.out.print("Stack : ");
list.display();
}
}

class StackLinkedList
{
public static void main(String[] args) throws IOException
{
MyStack s= new MyStack();
s.push(10);
s.push(20);
s.displayStack();
s.push(30);
s.push(40);
s.displayStack();
s.pop();
s.pop();
System.out.println("Two elements are popped");
s.displayStack();
}
}

Save this program with StackLinkedList.java.


At command prompt:
D:\ JDS Programs>javac StackLinkedList.java
D:\JDS Programs>java StackLinkedList
Output:
Stack : Elements from top to bottom

Data Structures Prepared by Mahesh MCA


100
B.Sc. IV SEMESTER

20
10

Stack : Elements from top to bottom


40
30
20
10

Two elements are popped


Stack : Elements from top to bottom
20
10

//5.Write Programs to implement the Queue operations using a singly linked list
import java.io.*;
class MyNode
{
int item;
MyNode next;
MyNode(int val)
{
item = val;
}
void displayNode( )
{
System.out.print(item+" " );
}
}
class MyLinkedList
{
MyNode start;
MyNode end;
boolean isEmpty( )
{
return start==null;
}
void insertEnd(int val)
{
MyNode newNode = new MyNode(val);
if( isEmpty( ) )
start = newNode;
else
end.next = newNode;
end = newNode;
}
int deleteStart( )
{
int temp = start.item;
if(start.next == null)

Data Structures Prepared by Mahesh MCA


101
B.Sc. IV SEMESTER

end = null;
start = start.next;
return temp;
}
void displayList( )
{
MyNode current = start;
while(current != null)
{
current.displayNode();
current = current.next;
}
System.out.println(" ");
}
}
class MyQueue
{
MyLinkedList list;
MyQueue( )
{
list= new MyLinkedList( );
}
boolean isEmpty( )
{
return list.isEmpty( );
}
void insert(int k)
{
list.insertEnd(k);
}
int delete( )
{
return list.deleteStart( );
}
void display( )
{
System.out.print("Queue [start to end]: ");
list.displayList( );
}
}
class QueueLinkedList
{
public static void main(String[ ] args)
{
MyQueue demo = new MyQueue( );
System.out.println("Inserting two elements into the queue");
demo.insert(10);
demo.insert(20);
demo.display( );
System.out.println("Inserting one more element into the queue at the end");

Data Structures Prepared by Mahesh MCA


102
B.Sc. IV SEMESTER

demo.insert(30);
demo.display( );
System.out.println("Deleting one element from the front");
demo.delete( );
demo.display( );
}
}

Save this program with QueueLinkedList.java.

At command prompt:
D:\ JDS Programs>javac QueueLinkedList.java
D:\JDS Programs>java QueueLinkedList

Output:
Inserting two elements into the queue
Queue [start to end]: 10 20
Inserting one more element into the queue at the end
Queue [start to end]: 10 20 30
Deleting one element from the front
Queue [start to end]: 20 30

//6) Write a Java program for implementation of QuickSort?


class QuickSort
{
/* This function takes last element as pivot, places the pivot element at its correct
position in sorted array, and places all smaller (smaller than pivot) to left of
pivot and all greater elements to right of pivot */

int partition(int arr[ ], int low, int high)


{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or equal to pivot
if (arr[ j] <= pivot)
{
i++;
// swap arr[ i] and arr[ j]
int temp = arr[i];
arr[i] = arr[ j];
arr[ j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;

Data Structures Prepared by Mahesh MCA


103
B.Sc. IV SEMESTER

}
/* The main function that implements QuickSort( )
arr[ ] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void sort(int arr[ ], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}

/* A utility function to print array of size n */


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

public static void main(String args[])


{
int arr[ ] = {10, 7, 8, 9, 1, 5};
int n = arr.length;

QuickSort ob = new QuickSort( );


ob.sort(arr, 0, n-1);

System.out.println("Sorted Array:");
printArray(arr);
}
}

Save this program with QuickSort.java


At command prompt:
D:\ JDS Programs>javac QuickSort.java
D:\JDS Programs>java QuickSort
Press enter key
Output:
Sorted Array:
1 5 7 8 9 10

Data Structures Prepared by Mahesh MCA


104
B.Sc. IV SEMESTER

//7) Write a Java program for implementation of Binary Search

class BinarySearchExample
{
public static void binarySearch(int arr[ ], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if (arr[mid] == key)
{
System.out.println("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");
}
}
public static void main(String args[ ])
{
int arr[ ] = {10,20,30,40,50};
int key = 40;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

Save this program with BinarySearchExample.java


At command prompt:
D:\ JDS Programs>javac BinarySearchExample.java
D:\JDS Programs>java BinarySearchExample
Press enter key
Output:

Element is found at index: 3

Data Structures Prepared by Mahesh MCA


105
B.Sc. IV SEMESTER

//8) Write a Java program for implementation of Linear Search (or) Sequential
public class LinearSearchExample
{
public static int linearSearch(int[] arr, int key)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i] == key)
{
return i;
}
}
System.out.println("searching element was not found in the array");
return -1;
}
public static void main(String a[ ])
{
int a1[ ]= {10,20,30,50,70,90};
int key = 70;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

Save this program with StackLinkedList.java.


At command prompt:
D:\ JDS Programs>javac LinearSearchExample.java
D:\JDS Programs>java LinearSearchExample

Output:
70 is found at index: 4

//9) Write a Java program to implement the Selection Sort?


/* Following Java Program ask to the user to enter the array size and array elements, then it will sort the
array in ascending order and display the sorted array: */
/* Java Program Example - Selection Sort */

import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
int size, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");


size = scan.nextInt();

System.out.print("Enter Array Elements : ");


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

Data Structures Prepared by Mahesh MCA


106
B.Sc. IV SEMESTER

{
arr[i] = scan.nextInt();
}

System.out.print("Sorting Array using Selection Sort Technique:\n");


for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.print("Now the Array after Sorting is :\n");


for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}

Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Selection Sort Technique:
Now the Array after Sorting is:
12 23 45 76 87 98

//10) Write a Java program to implement the Insertion Sort?


/*Following Java Program ask to the user to enter array size and array elements to sort the array using the
insertion sort technique, then display the sorted array on the screen:*/
/* Java Program Example - Insertion Sort */

import java.util.Scanner;

public class JavaProgramIns


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

Data Structures Prepared by Mahesh MCA


107
B.Sc. IV SEMESTER

int size, i, j, temp;


int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");


size = scan.nextInt();

System.out.print("Enter Array Elements : ");


for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Sorting Array using Insertion Sort Technique:\n");


for(i=1; i<size; i++)
{
temp = arr[i];
j = i - 1;
while((temp < arr[j]) && (j >= 0))
{
arr[j+1] = arr[j];
j = j - 1;
}
arr[j+1] = temp;
}

System.out.print("Array after Sorting is : \n");


for(i=0; i<size; i++)
{
System.out.print(arr[i] + " ");
}
}
}

Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Insertion Sort Technique:
Now the Array after Sorting is:
12 23 45 76 87 98

Data Structures Prepared by Mahesh MCA


108
B.Sc. IV SEMESTER

//11) Write a Java program to implement the Bubble Sort?


import java.util.Scanner;
class BubbleSort
{
public static void main(String args[ ])
{
int n, i, j, swap;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of integers to sort:");
n = in.nextInt();
int array[ ] = new int[n];
System.out.println("Enter " + n + " elements:");

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


{
array[i] = in.nextInt( );
}
for (i = 0; i < ( n - 1 ); i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (array[ j] > array[ j+1]) /* For descending order use < */
{
swap = array[j];
array[ j] = array[j+1];
array[ j+1] = swap;
}
}
}
System.out.println("Sorted list of numbers:");
for (i = 0; i < n; i++)
System.out.print(" "+array[i]);
}
}

Output:
Enter number of integers to sort:
6
Enter 6 elements:
8
4
6
11
3
10
Sorted list of numbers:
3 4 6 8 10 11

Data Structures Prepared by Mahesh MCA

You might also like