Data Structures Notes
Data Structures Notes
B.Sc. IV SEMESTER
External Sorts
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.
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
Example
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.
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.
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
Example:
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.
1. Compare each pair of adjacent elements from the beginning of an array and,
if they are in reversed order, swap them.
Bubble_Sort ( A [ ] , N )
Step 3 : If ( A [ J ] < A [ J – 1 ] )
Swap ( A [ J ] , A [ J – 1 ] )
Step 4 : Exit
Example
int n , temp ,i , j;
System.out.println( );
n = arr.length; temp = 0;
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
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.
if length(q) ≤ 1
return q
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.
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
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
Example:
for(int i:inputArr)
mms.sort(inputArr);
for(int i:inputArr)
this.array = inputArr;
this.length = inputArr.length;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
tempMergArr[i] = array[i];
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
array[k] = tempMergArr[i];
i++;
else {
array[k] = tempMergArr[j];
j++;
k++;
array[k] = tempMergArr[i];
k++;
i++;
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.
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.
item = 19
ELEMENT FOUND
This function returns an index position ‗i' if the element is found; otherwise,
return -1.
Time Complexity:
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.
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.
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);
}
}
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);
}
}
MyStack(int size)
{
top = -1;
item = new int[size];
}
void popItem( )
{
if (top < 0)
{
System.out.println("Stack is Empty");
}
else
{
top--;
System.out.println("Pop Item : " + item[top+1]);
}
}
}
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);
}
}
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
1
Enter Push Item :
77
Pushed Item : 77
___________________
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
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]);
}
}
}
}
}
//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("");
}
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();
}
}
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)
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");
demo.insert(30);
demo.display( );
System.out.println("Deleting one element from the front");
demo.delete( );
demo.display( );
}
}
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
}
/* 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);
}
}
System.out.println("Sorted Array:");
printArray(arr);
}
}
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);
}
}
//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));
}
}
Output:
70 is found at index: 4
import java.util.Scanner;
{
arr[i] = scan.nextInt();
}
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
import java.util.Scanner;
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
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