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

DSA StdsCopy

A linked list is a data structure consisting of nodes connected by links, with each node containing data and a reference to the next node. There are various types of linked lists, including simple, doubly, and circular linked lists, each allowing different navigation capabilities. The document also details basic operations such as insertion, deletion, and searching within linked lists, along with algorithms for these operations.

Uploaded by

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

DSA StdsCopy

A linked list is a data structure consisting of nodes connected by links, with each node containing data and a reference to the next node. There are various types of linked lists, including simple, doubly, and circular linked lists, each allowing different navigation capabilities. The document also details basic operations such as insertion, deletion, and searching within linked lists, along with algorithms for these operations.

Uploaded by

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

• Linked lists

• A linked list is a sequence of data structures connected via links.


• A Linked List is a sequence of links containing items. Each link contains a connection
to another link. Linked lists are the second most-used data structure after arrays.
• Following are the important terms to understand the concept of Linked List.
• Link − Each link of a linked list can store data, which is called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• LinkedList − A Linked List contains the connection link to the first link, First.
• Linked List Representation
• A linked list can be visualized as a chain of nodes, where every node points to the
next node.

• As per the above illustration, the following are the important points to be considered.
• Linked List contains a link element called first.
• Each link carries a data field(s) and a link field called next.
• Each link is linked with its next link using its next link.
• The last link carries a null link to mark the list’s end. 1
• Types of Linked List • Simple way to create a linked list
• Following are the various types of linked using “import java.util.LinkedList;”
lists. 1. import java.util.LinkedList;
• Simple Linked List − Item navigation is 2. public class Linky {
forward only. 3. public static void main(String[] args) {
• Doubly Linked List − Items can be navigated 4. LinkedList linky = new LinkedList();
forward and backward. 5. linky.add("A");
• Circular Linked List − The last item links to 6. linky.add("B");
the first element as the next, and the first 7. linky.add("C");
element has a link to the last element as the 8. System.out.println(linky);
previous. 9. }
10. }
• Basic Operations
• Following are the basic operations 11. import java.util.LinkedList;
12. public class Linky {
supported by a list. 13. public static void main(String[] args) {
• Insertion − Adds an element at the beginning 14. LinkedList linky = new LinkedList();
of the list. 15. linky.add("A");
• Deletion − Deletes an element at the 16. linky.add("B");
beginning of the list. 17. linky.add("C");
• Display − Displays the complete list. 18. System.out.println(linky);
• Search − Searches an element using the given 19. linky.remove();//it removes from font
key. 20. System.out.println(linky);
• Delete − Deletes an element using the given 21. } 2
22. }
1.
2.
import java.util.LinkedList;
public class Linky {
• Other way to create a simple linked list
1. public class LLIntroduction {
3. public static void main(String[] args) {
2. Node head;//head of list
4. LinkedList linky = new LinkedList(); 3. //linked list node
5. linky.add("A"); 4. static class Node{
6. linky.add("B"); 5. int data;
7. linky.add("C"); 6. Node next;
8. System.out.println(linky); 7. //constructor to create a new node
9. linky.remove();//it removes from font 8. Node(int d){
10. System.out.println(linky); 9. data=d;
10. next=null;
11. linky.clear();//it removes all the nodes
11. }
12. System.out.println(linky);
12. }
13. } 13. public static void main(String[] args) {
14. } 14. // TODO Auto-generated method stub
15. //empty linked list
15. import java.util.LinkedList; 16. LLIntroduction emptyList = new LLIntroduction();
16. public class Linky { 17. //creating nodes
17. public static void main(String[] args) { 18. emptyList.head=new Node(10);
19. Node secondNode= new Node(16);
18. // TODO Auto-generated method stub
20. Node thirdNode=new Node(21);
19. LinkedList linky = new LinkedList();
21. //linking the created nodes with empty linkedlist
20. linky.add("A");
22. emptyList.head.next=secondNode;
21. linky.add("B"); 23. secondNode.next=thirdNode;
22. linky.add("C"); 24. emptyList.printLinkedList();
23. System.out.println(linky); 25. }
24. //linky.remove();//it removes from font 26. //method for printing the linked list items
25. //System.out.println(linky); 27. private void printLinkedList() {
26. //linky.clear();//it removes all the nodes 28. Node tempNode=head;
29. while(tempNode!=null) {
27. //System.out.println(linky);
30. System.out.println(tempNode.data+" ");
28. System.out.println(linky.getFirst());
31. tempNode=tempNode.next;
29. System.out.println(linky.getLast());
32. }
30. } 33. } 3
31. } 34. }
• Linked List-Insert Node (At Front, At Center, At End) • How to delete an element from linked list-
• Add the below ”insertAtFront()” method code after the ”printLinkedList()” method
• //method for inserting a node at front
• Whenever you are trying to delete an element from a linked
• private void insertAtFront(int datavalue) { list you suppose to use index value.
• //create a new node
• Node newNode = new Node(datavalue); • Create a method like deleteAt(int index).


newNode.next=head;//connecting new node to the existing head node
head=newNode;//now newnode became head
public void deleteAt(int index)
• }
{
• Add the below code in “main()” method and run. //in case if you want to delete 1st node/element (which is head
• emptyList.insertAtFront(5); element) use the following code
• emptyList.printLinkedList();
if(index==0)
• Add the below “insertAt()” method code after the
“insertAtFront()” method
{
• private void insertAt(int index, int datavalue) { head=head.next;
• Node n=head;
• Node newNode = new Node(datavalue); }
else // if you want to delete other elements use the following
• for(int i=0;i<index-1;i++) {
• n=n.next;
• } logic. (you need to traverse up to that element)
• newNode.next=n.next;
• n.next=newNode; {

• }
Add the below code in “main()” method and run
Node n= head;// creating new node 'n' and assigning the 'head'
• emptyList.insertAt(1, 12); to 'n'
• emptyList.printLinkedList();
Node n1=null;
• Add the below “insertAtEnd()” method code after the “insertAt()” method for(int i=0;i<index-1;i++)// this loop is used to traverse before
• private void insertAtEnd(int datavalue) {
• //create a new node the given location index value


Node newNode = new Node(datavalue);
Node end = head;
{


while(end.next!=null) {
end=end.next;
n=n.next;
• } }
• end.next=newNode;
• } n1=n.next;
• Add the below code in “main()” method and run.
n.next=n1.next;
• emptyList.insertAtEnd(29); }
• emptyList.printLinkedList("\nAfter Insertion at end"); 4
}
• length of the linked list • Linked list Node creation algorithm
• Add the below “findLength()” method code after the • Step1 : initialize Node class
“deleteAt()” method • Step2: initialize data
• private int findLength() {


Node current = head;
int count=0;
• Step3: initialize next


while (current!=null) {
current=current.next;
• Step4: initialize Node constructor


count=count+1;
}
• Step5: set data=data


return count;
}
• Step6: set next=null
• Add the below code in “main()” method and run. • Step7: exit
• int len=emptyList.findLength();
• System.out.println("\nthe length of the linked list:"+len);
• Traverse a linked list algorithm
• Search of the node • Step1: initialize set tempnode=head
• Add the below “searchNode()” method code after • Step2: repeat steps 3 to 4 while(tempnode!=null)
the “findLength()” method • Step3: write tempnode.data
• private boolean searchNode(int value) {


Node temp= head;
while(temp!=null) {
• Step4: set tempnode=tempnode.next


if(temp.data==value) {
return true;
• End of loop


}
temp=temp.next;
• Step5: exit
• }


return false;
}
• Insert a node at the beginning of LL - algorithm
• Add the below code in “main()” method and run. • Step1: initialize head


boolean found=emptyList.searchNode(16);
if(found) {
• Step2: initialize set newnode=datavalue


System.out.println("Node is Available");
}
• Step3: initialize set newnode.next=head


else
{
• Step4: initialize set head=newnode


System.out.println("Node Not Available");
}
• Step5: exit 5
• Insert a node at the given location algorithm • Delete node using the given location algorithm
• Step1: initialize set n=head • Step1: initialize set n=head
• Step2: initialize set n1=null
• Step2: initialize set newnode=datavalue
• Step3: initialize set index (based on given index)
• Step3: repeat steps 3 to 4 while(i<index-1) • Step4: repeat steps 3 to 4 while(i<index-1)
• Step4: initialize set n=n.next • Step5: set n=n.next
• End of loop • End of loop
• Step5: set newnode.next=n.next • Step6: set n1=n.next
• Step6: set n.next=newnode • Step7: n.next=n1.next
• Step8: exit
• Step7: exit
• Length of the linked list algorithm
• Insert a node at the end algorithm • Step1: initialize set current=head
• Step1: initialize set newnode=datavalue • Step2: initialize set count=0
• Step2: initialize set end=head • Step3: repeat steps 3 to 5 while(current!=null)
• Step3: repeat steps 3 to 4 while(end.next!=null) • Step4: set current=current.next
• Step4: set end=end.next • Step5: set count=count+1
• End of loop
• End of loop
• Step6: return count
• Step5: set end.next=newnode • Step7 exit
• Step6: exit
• Searching a node algorithm
• Delete front/starting/head node algorithm • Step1: initialize set temp=head
• Step1: initialize set temp=head • Step2: repeat steps 3 to 4 while(temp!=null)
• Step2: initialize key (based on node value/data) • Step3: if temp.data==value
• Return true
• Step3: initialize set prev=null
• Step4: set temp=temp.next
• Step4: if(temp!=null && temp.data==key) • End of loop
• Step5: set head=temp.next • Return false
• Step6: exit 6
• Step5: exit
• Doubly Linked List • Doubly Linked List Representation
• It is called 2 way linked list.
• A doubly linked list is a variation of a
Linked list in which navigation is
possible in both directions, forward • As per the above illustration, following
and backward, easily compared to a are the important points to be
Single Linked List. considered:
• Following are the important terms to • Head points to the first node, tail points
understand the concept of a doubly to the last node.
linked list. • Each node carries a data field and two link
• Data − Each data/link of a linked list can fields called next and prev.
store data called an element. • Each node is linked with its next link using
• Next − Each link of a linked list contains a its next link.
link to the next link called Next. • Each node is linked with its previous link
• Prev − Each link of a linked list contains a using its previous link.
link to the previous link called Prev. • The last node carries a link as null to mark
the end of the list.

7
46. while(temp!= null)
1. import java.util.List; 25. public void
47. {
insertFirst(int value) {
2. public class DLL { 26. //create a list node
48. System.out.print(temp.data + "-->");
49. temp=temp.next;
3. ListNode head; like below and assign the
50. }
value to it
4. ListNode tail; 51. System.out.println("Null");
27. ListNode newNode = 52. }
5. private int length; new ListNode(value); 53. public void displayBackward() {
6. public DLL() { 28. if(isEmpty())//here 54. {
im checking DLL is empty 55. if (tail == null) {
7. this.head = null; or not 56. return;
8. this.tail = null; 29. { 57. }
30. tail=newNode; 58. ListNode temp = tail;
9. this.length = 0; 59. while (temp != null) {
31. }
10. } 60. System.out.print(temp.data + "-->");
32. else
11. private class ListNode { 33. 61. temp = temp.previous;
{ 62. }
12. private int data; 34. 63. System.out.println("Null");
head.previous=newNode 64. }
13. private ListNode next; ; 65. }
14. private ListNode previous;
35. } 66. public static void main (String[]args){
15. public ListNode(int data)
36.{ 67. DLL dll = new DLL();
newNode.next=head; 68. dll.insertFirst(5);
16. this.data = data; 69. dll.insertFirst(10);
37. head=newNode;
17. } 38. length=length+1;
70. dll.insertFirst(15);
71. dll.insertFirst(20);
18. } 39. } 72. dll.displayForward();
19. public boolean isEmpty() 40.
{ public void 73. dll.displayBackward();
displayForward() { 74. }
20. return length == 0; 41. if(head==null) 75. }
21. } 42. {
22. public int length() { 43. return;
44. }
23. return length;
45. ListNode temp =
24. } head; 8
DLL implementation • Creating a constructor for a DLL class to assign the
Create a new class DoublyLinkedList.java and represent the node as values of the instance variables like below in
follows: DoublyLinkedList.java:
public class DoublyLinkedList {
//in this case we need a list node class(this is inner class), //Creating a constructor for a DLL class
in SLL, I created node.java separately, but here im creating to assign the values of the instance
inside the DLL.java only
private class ListNode
variables
{ //when we initialize the DLL, the list
//in this node there are 3 components, previous, data, next,
here i am declaring those 3 components
will be empty
private int data; public class DoublyLinkedList {
private ListNode next;
private ListNode previous; public DoublyLinkedList()
//create a constructor to take data part
public ListNode(int data) {
{
this.data = data; this.head=null;
}
} this.tail=null;
}
this.length=0;
Like, in Singly linked list we are representing the node of DLL.
}
• In DLL we have head & tail pointers, so we create two }
instance variables of ListNode like below in • Create a method isempty() as below in DLL.java class to
DoublyLinkedList.java: check whether DLL is empty or not:
public class DoublyLinkedList { public boolean isempty()
{
//we create two instance variables of ListNode return length==0; //in this case if lenght=0 or head=null it will say
DLL is empty.
private ListNode head;//head will be the 1st
}
node
private ListNode tail;//tail will be the last • Create a method length() as below in DLL.java class to
node return back the length of the DLL:
//create a variable length to hold the number public int length()
{
of elements in the DLL
return length; 9
private int length; }
• How to insert node at the beginning of a • to save time and minimize the complexity of
Doubly Linked List in Java ? the student I’m writing the main method
• Algorithm inside the DLL class only
ListNode newNode=new ListNode(value); public class DoublyLinkedList
if(isempty()) {
{ public static void main (String[] args)
{
tail=newNode; DoublyLinkedList dll = new DoublyLinkedList();//created an object dll of
} DoublyLinkedList
dll.insertfirst(1);
else dll.insertfirst(10);
{ dll.displayforward();
}
head.previous=newNode;
}
}
newNode.next=head; • Create a method displayforward()to display
Head=newNode;
the list of elements in forward direction and
• Create a method in DLL.java class to insert a node at write DLL.java class:
first like below: public void displayforward()
public void insertfirst(int value)
{
{
//create a list node like below and assign the value to it if(head==null)
ListNode newNode = new ListNode(value); {
if(isempty())//here im checking DLL is empty or not return;
{ }
tail=newNode;
ListNode temp = head;
}
else while(temp!= null)
{ {
head.previous=newNode; System.out.print(temp.data + "-->");
} temp=temp.next;
newNode.next=head;
}
head=newNode;
length=length+1; System.out.println("Null");
} } 10
• Create a method displaybackward()to display the list of • How to insert node at the end of a Doubly Linked List?
elements in backward direction and write DLL.java • Algorithm
class: 1. ListNode newNode = new ListNode(value);
2. if (isempty())
public void displaybackward()
3. {
{ 4. head=newNode;
if(tail==null) 5. }
{ 6. Else
7. {
return;
8. tail.next=newNode;
} 9. newNode.previous=tail;
ListNode temp=tail; 10. }
11. tail=newNode;
while(temp!=null)
{
public void insertlast(int value)
System.out.print(temp.data + "-->");
{
temp=temp.previous; ListNode newNode = new ListNode(value);
} if(isempty())
System.out.println("Null"); {
head=newNode;
}
}
else
{
tail.next=newNode;
newNode.previous=tail;
}
tail=newNode;
}

11
• How to delete first node in a Doubly Linked public ListNode delfirst()
{
List? if(isempty())
• Algorithm {
if(isempty()) throw new NoSuchElementException();//import like this
-- import java.util.NoSuchElementException;
{ }
Raise Exception; ListNode temp=head; //creating temp variable like a
ListNode and assigning head to it
}
if(head==tail)//if it is true, DLL will be having
ListNode temp= head; only one node
if(head==tail) {
{ tail=null;
}
tail=null;
else
}
{
else head.next.previous=null;
{ }
head.next.previous=null; head=head.next;
} temp.next=null;

head=head.next; length=length-1;//after deleting the element, the


length also come down
temp.next=null; return temp;
return temp; }
12
• How to delete last node in a Doubly public ListNode dellast()
Linked List {
if(isempty()) {
• Algorithm
throw new NoSuchElementException();
if(isempty())
}
{
ListNode temp=tail;
Raise Exception;
if(head==tail)
}
{
ListNode temp= tail;
head=null;
if(head==tail)
}
{
else
head=null;
{
}
else tail.previous.next=null;

{ }

tail.previous.next=null; tail=tail.previous;

} temp.previous=null;
tail=tail.previous; length=length-1;
temp.previous=null; return temp;
return temp; }
13
• Circular Linked List • As per the image illustration, following
• Circular Linked List is a variation of Linked list in are the important points to be
which the first element points to the last element
and the last element points to the first element. considered.
• Both Singly Linked List and Doubly Linked List can be • The last link's next points to the first link of
made into a circular linked list. the list in both cases of singly as well as
doubly linked list.
• Singly Linked List as Circular • The first link's previous points to the last of
• In singly linked list, the next pointer of the last node the list in case of doubly linked list.
points to the first node. • Basic Operations
• insert − Inserts an element at the start of
the list.
• delete − Deletes an element from the start
of the list.
• display − Displays the list.

14
1. public class CircularSLL { 24. public void createcsll()
25. {
2. static ListNode last; 26. //creating nodes
3. static ListNode head; 27. ListNode first=new ListNode(10);
4. private int length; 28. ListNode second=new ListNode(20);
29. ListNode third=new ListNode(30);
5. public CircularSLL() { 30. ListNode fourth=new ListNode(40);
6. last=null; 31. //inter connect the above 4 nodes like below
7. length=0; 32. first.next=second;
33. second.next=third;
8. } 34. third.next=fourth;
9. private class ListNode{ 35. fourth.next=first;
36. last=fourth;
10. private ListNode next;
37. head=first;
11. private int data; 38. }
12. public ListNode(int data){ 39. public static void show()
40. {
13. this.data=data;
41. ListNode temp = head;
14. } 42. while(temp.next !=head)
15. } 43. {
44. System.out.print(temp.data + " ");
16. public int length()
45. temp=temp.next;
17. { 46. }
18. return length; 47. System.out.println(temp.data);//printing last node
48. }
19. } 49. public static void main(String[] args) {
20. public boolean isempty() 50. // TODO Auto-generated method stub
21. { 51. CircularSLL csll = new CircularSLL();
52. csll.createcsll();
22. return length == 0; 53. csll.show();
23. } 54. }
55. }

15
• Doubly Linked List as Circular • This search algorithm works on the searching
• In doubly linked list, the next pointer of the position of the required value.
last node points to the first node and the • For this algorithm to work properly, the data
previous pointer of the first node points to the collection should be in a sorted form and
last node making the circular in both equally distributed.
directions. • Binary search has a huge advantage of time
complexity over linear search.
• Assignment to the students • Linear search has worst-case complexity of
Ο(n) whereas binary search has Ο(log n).
• Interpolation Search
• Interpolation search is an improved variant of
binary search.
• Interpolation search is a variation of Binary
search, meaning it is also a divide and conquer
algorithm how it differs is that rather than
dividing the input array into two equal parts it
tries to divide the array in such a way that the
position is nearer to the searched element.

16
• Points to be noted
1. public class InterpolationSearch {
2. public static void main(String[] args) {
3. int[] a={1,2,3,4,5,6,7,8,9};
• Elements to be sorted and uniformly 4. int index=is(a,1);
distributed. 5. if (index!=-1){
6. System.out.println("Element fount at
• Searching element (se)=???? index:"+ index);
7. }
• Start index(si)=0; 8. else{
9. System.out.println("Element not found");
• End index(ei)= size-1; 10. }
• Where size= number of elements in the array 11. }
12. private static int is(int[] a, int value) {
‘a’. 13. int high=a.length-1;
14. int low=0;
• Algorithm 15. while(value>=a[low] && value<=a[high] &&
low<=high){
• While(si<=ei && se>=a[si] && se<=a[ei]) 16. int
p=low+(high-low)*(value-a[low])/(a[high]-a[low]) ;
• Position(pos)=si+((si-ei)/(a[ei]-a[si]))*(se- 17. System.out.println("probe:"+p);
a[si]) 18. if(a[p]==value){
19. return p;
• If(a[pos]==se) , then the element is found 20. }
• If(se>a[pos]) , then make si=pos+1; 21.
22.
else if(a[p]<value){
low=p+1;
• If(se<a[pos]), then make ei=pos-1; 23. }
24. else{
• End of loop 25. high=p-1;
26. }
27. }
• Ask the students to work with the following dataset: 28. return -1;
29. } 17
1,2,4,8,16,32,64,128,256,1024 30. }
• Hashing Technique
• This technique is used to search the elements.
• Linear search will randomly take elements and O(n) time.
• Binary search will take elements in sorted order and take O(logn)
time.
• Hashing techniques, unlike linear and binary search, take the
elements randomly and operate in O(1) time, offering a significant
advantage in terms of efficiency.
• It stores the element in the array’s index equivalent to the value.
• This means that if element 8 wants to be inserted, it will be
stored in index 8 of an array.
• If you want to search for any element, you can directly visit the
index of that element.
• In this case, the search time is O(1) because you reach the search
element directly.
• You will face a problem whenever you want to insert an element
whose values are greater than the size of the array.
• For example, the size of the array is 12, but you want to insert 20.
In the array, we don’t have 20 indexes to store 20 elements.
• We can solve the above problem by using the properties of the
hashing function like the below:
1. One to one – h(x)=x
2. Many to one – h(x)=x % size of an array(hash table)
• We have different hash functions like
1. K mod 10,
2. K mod n,
3. mid square, and 18
4. folding method.
• Collision resolution methods
• Open hashing
• chaining
• Closed hashing
• Linear probing
• Quadratic probing

19
• Hash-Table • Linked HashMap
• Hash--table in Java is an in-built class; it creates a hash table by mapping
keys to values. • The Map interface is implemented as a Hashtable and
• Hash-Table implements the Map interface and inherits from the Linked list in Java's LinkedHashMap class.
Dictionary class. 1. import java.util.*;
2. public class LinkedHashMap1{
1. import java.util.*;
2. public class HT { 3. public static void main(String args[]){
3. // imports useful collection framework, collection classes, classes 4. LinkedHashMap<Integer,String> LHM=new
related to date and time, event model, internationalization, and LinkedHashMap<Integer,String>();
miscellaneous utility classes. etc
4. public static void main(String args[]){
5. /* Hashtable() constructor is used to declare an empty
5. LHM.put(16,"Virat");
Hashtable of default size and load factor below, we have used the 6. LHM.put(1,"Alex");
same for creating a hashtable named HT */ 7. LHM.put(40,"Ishika");
6. Hashtable<Integer,String> HT=new Hashtable<Integer,String>();
7. //Put(key,value) method helps us to store data in hashtable
8. LHM.put(5,"Sonu");
8. HT.put(16,"Umid"); 9. LHM.put(3,"Mrinalini");
9. HT.put(1,"Max"); 10. LHM.put(38,"John");
10. HT.put(40,"Sim"); 11.
11. HT.put(5,"Dildora");
12. HT.put(3,"Diyor");
12. System.out.println("Does it maintain insertion
13. HT.put(38,"Johon");
order? ....");
14. /* Now we loop through the hashtable HT and print each key-value
pair one by one 13. for(Map.Entry m:LHM.entrySet()){
15. */
14. System.out.println(m.getKey()+"
16. for(Map.Entry m:HT.entrySet()){
17. System.out.println(m.getKey()+" "+m.getValue());
"+m.getValue());
18. } 15. }
19. } 16. }
20. } 17. }
20
• Sorting Techniques • Bubble Sort Algorithm
• Sorting refers to arranging data in a particular • Bubble sort is a simple sorting
format. Sorting algorithm specifies the way algorithm.
to arrange data in a particular order. Most
common orders are in numerical or • This sorting algorithm is comparison-
alphabetical order. based algorithm in which each pair of
• The importance of sorting lies in the fact that adjacent elements is compared, and
data searching can be optimized to a very the elements are swapped if they are
high level, if data is stored in a sorted not in order.
manner. • This algorithm is not suitable for large
• Sorting is also used to represent data in more data sets as its average and worst-case
readable formats. complexity are of Ο(n2) where n is the
• Following are some of the examples of number of items, O is the order (Big
sorting in real-life scenarios −
O) , it is used to check the complexity
• Telephone Directory − The telephone directory
stores the telephone numbers of people sorted like avg, best, worst cases.
by their names, so that the names can be • How Bubble Sort Works?
searched easily.
• We take an unsorted array for our
• Dictionary − The dictionary stores words in an
alphabetical order so that searching of any word example. Bubble sort takes Ο(n2) time so
becomes easy. we're keeping it short and precise.
21
• Bubble sort starts with very first • The new array should look like this −
two elements, comparing them to
check which one is greater.
• Next, we compare 33 and 35. We
find that both are in already sorted
positions.
• In this case, value 33 is greater • Then we move to the next two
than 14, so it is already in sorted values, 35 and 10.
locations. Next, we compare 33 • We know then that 10 is smaller 35.
with 27. Hence, they are not sorted.

• We find that 27 is smaller than 33 • We swap these values. We find that


and these two values must be we have reached the end of the
swapped. array. After one iteration, the array
should look like this −
22
• To be precise, we are now showing • Algorithm
how an array should look like after • We assume list is an array of n
each iteration. After the second elements.
iteration, it should look like this − • We further assume that swap function
swaps the values of the given array
elements.
• Notice that after each iteration, at begin BubbleSort(list)
least one value moves at the end. for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
• And when there's no swap required,
end if
bubble sorts learns that an array is
end for
completely sorted.
return list
end BubbleSort

23
public class BubbleSort { import java.util.*;
public static void main(String[] args) { public class BubbleSort {
int[] a= {14,33,27,35,10}; public static void main(String[] args) {
int temp; String[] a= {"safan","Ali","Fadi","Mohammad","Gouse"};
for (int i = 0; i<a.length;i++) String temp;
{ for (int i = 0; i<a.length;i++)
int flag=0; {
for (int j = 0; j<a.length-1-i;j++ )//the -i
int flag=0;
is used to skip the comparison of last rounds
largest element for (int j = 0; j<a.length-1-i;j++ )//the -i is
used to skip the comparison of last rounds largest
{ element
/* compare the adjacent elements */
{
if (a[j] > a[j+1])
/* compare the adjacent elements */ if
{ (a[j].compareTo( a[j+1])>0)//this compareto() method
temp=a[j]; takes every character and converts to unicode and
a[j]=a[j+1]; compares with another
a[j+1]=temp; {
flag=1; temp=a[j];
} a[j]=a[j+1];
} a[j+1]=temp;
if(flag==0)//to avoid continuous looping,im flag=1;
using flag
}}
{
if(flag==0)//to avoid continuous looping,im using
break; flag
} {
}
break;
for(int i=0;i<a.length;i++)
}}
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ " ");
{
}
} System.out.print(a[i]+ " ");
24
} }
• Insertion Sort • How Insertion Sort Works?
• This is an in-place comparison-based • We take an unsorted array for our
sorting algorithm. example.
• Here, a sub-list is maintained which is
always sorted. • Insertion sort compares the first two
• For example, the lower part of an array is elements.
maintained to be sorted.
• An element which is to be inserted in this
sorted sub-list, has to find its appropriate • It finds that both 14 and 33 are already
place and then it has to be inserted there. in ascending order. For now, 14 is in
• Hence the name, insertion sort. sorted sub-list.
• The array is searched sequentially and
unsorted items are moved and inserted • Insertion sort moves ahead and
into the sorted sub-list (in the same compares 33 with 27.
array).
• This algorithm is not suitable for large
data sets as its average and worst case • And finds that 33 is not in the correct
complexity are of Ο(n2), where n is the
position.
number of items. 25
• It swaps 33 with 27. It also checks • However, swapping makes 27 and 10
with all the elements of sorted sub- unsorted.
list. Here we see that the sorted sub- • Hence, we swap them too.
list has only one element 14, and 27
is greater than 14. Hence, the sorted
sub-list remains sorted after • Again we find 14 and 10 in an
swapping. unsorted order.
• By now we have 14 and 27 in the
sorted sub-list. Next, it compares 33 • We swap them again. By the end of
with 10. third iteration, we have a sorted sub-
• These values are not in a sorted list of 4 items.
order.
• So we swap them. • This process goes on until all the
unsorted values are covered in a
sorted sub-list 26
• Algorithm • Pseudo code:
• Step 1 − If it is the first element, it is Int[] a={5,1,6,2,4,3}
already sorted. return 1; Int temp,j;
• Step 2 − Pick next element For(int i=1;i<a.length;i++)
• Step 3 − Compare with all elements in {
the sorted sub-list Temp=a[i];
• Step 4 − Shift all the elements in the J=i;
sorted sub-list that is greater than the
value to be sorted While(j>0 && a[j-1]>temp)
• Step 5 − Insert the value {
• Step 6 − Repeat until list is sorted A[j]=a[j-1];
J=j-1;
• Take some numbers and explain in }
programmatic way: 5,1,6,2,4,3 A[j]=temp
}
Print all the elements
27
public class InsertionSort {
public static void main(String[] args)
• Selection Sort
{ • Selection sort is a combination of
int[] a={5,1,6,2,4,3}; searching and sorting.
int temp,j; • First it identifies the smallest element
for(int i=1;i<a.length;i++)
in the list and replace in the 0th
{
temp=a[i];
position (index).
j=i; • Once again it searches which is the
while(j>0 && a[j-1]>temp) next smallest element and places it in
{ the 1st position (index).
a[j]=a[j-1];
• Like this it will do with the entire list.
j=j-1;
}
• In this selection sort, we will use two
a[j]=temp; lists, sorted list , unsorted list.
} • This algorithm is not suitable for large
for(int i=0;i<a.length;i++) data sets as its average and worst-case
{
complexities are of Ο(n2), where n is
System.out.print(a[i]+ " ");
the number of items.
}
} • Take some example and explain:
} 38,52,9,18,6,62,13 28
• Pseudo code public class Selection {
public static void main(String[] args) {
Declare array with list of elements // TODO Auto-generated method stub
int[] a= {38,52,9,18,6,62,13};
Int min, temp=0; int min,temp=0;
for(i=0;i<a.length;i++) for(int i=0;i<a.length;i++)
{ {
min=i;
int min=i; for(int j=i+1;j<a.length;j++)
for(j=i+1;j<a.length;j++) {
if(a[j]<a[min])
{ {
if(a[j]<a[min]) min=j;
}
{ }
min=j; temp=a[i];
a[i]=a[min];
} a[min]=temp;
} }

temp=a[i]; for(int i=0;i<a.length;i++)


{
a[i]=a[min]; System.out.println(a[i]+" ");
a[min]=temp; }
}
} }
29
• Merge Sort • Merge Sort
• Merge sort is one of the most
popular sorting algorithms and
widely used technique.
• Its time complexity is better as
compared to bubble sort, selection
sort, and insertion sort.
• Merge sort works on divide and
conquer rule.
• In merge sort we use 2 functions, one
merge() function, it is used for merging
2 halves. Second, mergesort() function,
it is used for calling itself (recursively)
to divide38 the array
27 43 3 9 till
82 size
10 becomes
one.
• Ex:
demonstrate
30
• Algorithm 1. Merge(l,r,a)
• Merge sort keeps dividing the list into equal halves until it can 2. {
no longer be divided. 1. Nl=length(l)
• 2. Nr=length(r )
By definition, if only one element is in the list, it is sorted.
3. i=j=k=0
Then, merge sort combines the smaller sorted lists keeping
4. While(i<nl && j<nr)
the new list sorted too.
5. {
1. If(l[i]<=r[j])
• Step 1 − if there is only one element in the list, it is already 2. {
sorted, return. 1. A[k]=l[i]
• Step 2 − divide the list recursively into two halves until it 2. i=i+1
3. }
can no longer be divided. 4. Else
• Step 3 − merge the smaller lists into new lists in sorted 5. {
order. 1. A[k]=r[j]
• Pseudo Code: 2. J=j+1
6. }
• Mergesort(A) 7. K=k+1
• { 6. }
• n=length(a)
7. While(i<nl)
• If(n<2)
• Return 8. {
• Mid=n/2 1. A[k]=l[i]
• Left=array of size(0 to mid-1) 2. i=i+1
• Right=array of size(mid – (n-1)) 3. K=k+1
• For(i=0 to mid-1) 9. }
• Left[i]=a[i]
• For(i=mid to n-1)
10. While(j<nr)
• right[i-mid]=a[i] 11. {
• Mergesort(left) 1. A[k]=r[j]
• Mergesort(right) 2. J=j+1
• Merge(l,r,a) 3. K=k+1 31
• }
1. import java.util.Arrays; 20. public static void merge(int[] arr, int[] left, int[] right) {
2. public class MergeSort { 21. int i = 0, j = 0, k = 0;
3. public static void mergeSort(int[] arr) { 22. int n1 = left.length, n2 = right.length;
4. int n = arr.length; 23. // Merge the sorted subarrays
5. if (n > 1) { 24. while (i < n1 && j < n2) {
6. // Divide the array into two halves 25. if (left[i] <= right[j]) {
7. int mid = n / 2; 26. arr[k++] = left[i++];
27. } else {
8. int left[] = new int[mid];
28. arr[k++] = right[j++];
9. int right[] = new int[n - mid];
29. }
10. // Copy data to left and right subarrays
30. }
11. System.arraycopy(arr, 0, left, 0, mid);
31. // Copy remaining elements from left array
12. System.arraycopy(arr, mid, right, 0, n - mid);
32. while (i < n1) {
13. // Recursively sort left and right subarrays 33. arr[k++] = left[i++];
14. mergeSort(left); 34. }
15. mergeSort(right); 35. // Copy remaining elements from right array
16. // Merge the sorted subarrays 36. while (j < n2) {
17. merge(arr, left, right); 37. arr[k++] = right[j++];
18. } 38. }
19. } 39. }
32
40. public static void main(String[] args) {

41. int[] arr = {12, 11, 13, 5, 6, 7};

42. System.out.println("Original array:");

43. System.out.println(Arrays.toString(arr));

44. mergeSort(arr);

45. System.out.println("Sorted array:");

46. System.out.println(Arrays.toString(arr));

47. }

48. }

33
• Shell Sort
• Shell sort is an algorithm that first sorts the
elements far apart from each other and
successively reduces the interval between
the elements to be sorted.
• It is a generalized version of insertion sort
and bubble sort.
• It is more efficient than insertion or bubble
sort.
• Algorithm • Pseudo Code
• Step1 – take input array & size of array as ShellSort(arr,n)
{
‘n’. for (int gap = n / 2; gap > 0; gap /= 2) {

• Step2 – initialize the value of gap or interval for (int i = gap; i < n; i++) {
int temp = arr[i];
(gap=n/2) int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
• Step3 – compare the elements at the arr[j] = arr[j - gap];
distance of gap at every iteration. }
arr[j] = temp;
• Step4 - If the element at the left is larger }

than element at the right, perform swap or }


}

shift. Note : ask the students to write a java program to implement above pseudo
34
• Step5 – repeat until complete list is sorted. code.
• public class ShellSort {
• public static void shellSort(int[] arr) {
• int n = arr.length;
• for (int gap = n / 2; gap > 0; gap /= 2) {
• for (int i = gap; i < n; i++) {
• int temp = arr[i];
• int j;
• for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
• arr[j] = arr[j - gap];
• }
• arr[j] = temp;
• }
• }
• }
• // Example usage
• public static void main(String[] args) {
• int[] arr = {12, 34, 54, 2, 3};
• shellSort(arr);
• System.out.println("Sorted array is:");
• for (int num : arr) {
• System.out.print(num + " ");
• }
• }
• }

35
• Quick Sort • List : 15,9,7,13,12,16,4,18,11 34. void rec(int[]
• It has another name called as Partition-Exchange sort. 1. public class QuickSort { arr,int low,int
• Compared to any other sorts, this sort is very fast, and it is proved and 2. public static void
implemented. main(String[] args) { high)
• It is developed by Tony Hoare in 1959. 3. // TODO Auto-generated 35. {
• It is using the concept of divide and conquer. method stub
• In this, you should choose one random element, which is called as pivot element. 4. int[] arr= 36. int
{15,9,7,13,12,16,4,18,11}; pi=partition(arr,
• Options to select pivot element: you can choose first element , or middle element,
5. int l=arr.length;
or last element. low,high);
• Better to choose middle element. 6. QuickSort qs = new
QuickSort(); 37. if(low<pi-1)
• Pseudo Code 7. qs.rec(arr, 0, l-1);
Quicksort(l,h) 8. qs.printarray(arr); 38. {
{ 9. } 39. rec(arr,low,pi-
10. int partition(int[] arr,int
If(l<h)
low,int high) 1);
{
J=partition(l,h);
11. { 40. }
12. int pivot=arr[(low+high)/2];
Quicksort(l,j); 41. if(pi<high)
13. while(low<=high)
Quicksor(j+1,h); 14. {
} 42. {
15. while(arr[low]<pivot)
} 16. { 43. rec(arr,pi,high);
Partition(l,h) 17. low++;
18. } 44. }
{
Pivot=a[l]
19. while(arr[high]>pivot) 45. }
20. {
i=l, j=h;
21. high--; 46. void
while(i<j) printarray(int[]
22. }
{
Do
23. if(low<=high) arr)
24. {
{
25. int temp=arr[low]; 47. {
i++;
}While(a[i]>=piovot); 26. arr[low]=arr[high]; 48. for(int i:arr)
Do 27. arr[high]=temp;
{ 49. {
J--; 28. low++;
} While(a[j]<=pivot); 29. high--; 50. System.out.printl
If(i<j)
30. } n(i);
Swap(a[i],a[j])
} 31. } 51. }
Swap(a[l],a[j]) //if I > j then swap will perform 32. return low; 52. }
Return j;
33. }
53. } 36
}
• Graphs
• Graph is a set of (V,E) pairs, where V is set of
vertices, E is set of edges.
• Graphs has closed loop; trees has open loop.
• Vertices – represented as circles , also known
as nodes.
• Edges – represented as lines, which are
connecting two vertices or nodes.
• Terminology of Graph
• Node – which is nothing but vertices,
represented as circles.
• Edge – which is a line, it’s a connection
between the 2 different nodes.
• Adjacent Nodes - Two node or vertices
are adjacent if they are connected to each
other through an edge.
• Degree of a Node – it represents the number of
edges connected to the corresponding node.
• Size of graph – total number of edges in graph.
• Path – sequence of vertices from source node 37
to destination node.
• Types of Graphs
1. Directed graph – direction will be available in
the graph.
• In this every edge specified with direction.
• In one direction only we can traverse.
• This is a unidirectional graph.
• (A,B)#(not equal) (B,A)
2. Undirected graph – no direction will be available
in the graph.
• In undirected graph, you can traverse from AB == BA
or (A,B)==(B,A)
• In both the directions we can travel.
• This is a Bi-Directional graph.
3. Weighted graph – in this graphs the weight is
specified for every edge.
4. Unweighted graph – in this graphs there is no
weights for the edges.
5. Cyclic graph – means it should perform loops,
the path should be the same.
• ABCDA (starting point and ending points are the
same)
6. Acyclic graph – it should not perform loops, the
path not be the same. 38
• ABC (starting point and ending points are different)
• Graph algorithms are methods used to
manipulate and analyze graphs, solving
various problems, such as finding the
shortest path and cycle detection.
• Representation of Graph
• We can represent a graph in two ways:
1. Multidimensional array
2. Linked Lists
1. Multidimensional Array
• Rows and columns are represented by Nodes.
• You need to fill the array with 0’s and 1’s.
• If any edge between the 2 nodes or vertices, it
will be represented by 1, otherwise by 0.
2. Linked List
• The edges are denoted by linked list node.
• You need to fill the array with 0’s and 1’s.
• If any edge between the 2 nodes or vertices, it
will be represented by 1, otherwise by 0.
https://www.jdoodle.com/online-java-compiler/

39
1. import java.util.Scanner; 28. public static void main(String[] args)
2. public class AdjMatrixGraph { 29. {
3. //data members vertices, matrix
30. Scanner s=new
4. int vertices;
Scanner(System.in);
5. int matrix[][];
6. //creating constructor
31. System.out.println("Enter the
number of vertices");
7. AdjMatrixGraph(int vertices)
8. { 32. int V = s.nextInt();
9. this.vertices=vertices; 33. AdjMatrixGraph amg = new
10. matrix=new int[vertices][vertices]; AdjMatrixGraph(V);
11. } 34. System.out.println("Enter the
12. void addEdge(int source, int destination) number of edges");
13. { 35. int E=s.nextInt();
14. matrix[source][destination]=1;
36. for(int i=0;i<E;i++){
15. matrix[destination][source]=1;
16. }
37. System.out.println("Enter
the source vertex");
17. void printGraph()
18. { 38. int a=s.nextInt();
19. for(int i=0;i<vertices;i++) 39. System.out.println("Enter
20. { the destination vertex");
21. for(int j=0;j<vertices;j++) 40. int b=s.nextInt();
22. { 41. amg.addEdge(a,b);
23. System.out.print(matrix[i][j]+ "
"); 42. }
24. } 43. amg.printGraph();
25. System.out.println(); 44. }
40
26. } 45. }
Implementing the graph using the linked list(using java linked list utility) 24. void displayGraph()
representation 25. {
1. import java.util.LinkedList; 26. for(int i=0;i<vertices;i++)
2. public class Graph { 27. {
3. //instance varaibles 28. //if the size of the linked list is > 0
4. int vertices; 29. if(adjList[i].size()>0)
5. //need to be create an array of linked lists 30. {
6. LinkedList<Integer> adjList[]; 31. System.out.println("Vertex "+ i + "
7. //create a constructor to initialize the is connected to:-");
values to instance variables 32. for(int j=0;j<adjList[i].size();j+
8. public Graph(int vertices) +)
9. { 33. {
10. this.vertices=vertices; 34. //get() method returns the element at the
specified position in the list.
11. //we are allocating memory to our
adjacency list 35.
System.out.print(adjList[i].get(j)+" ");
12. adjList=new LinkedList[vertices];
36. }
13. for(int i=0;i<vertices;i++)
37. System.out.println();
14. {
38. }
15. //here for every node, it will create
a linked list. 39. }
16. adjList[i]= new LinkedList<>(); 40. }
41. public static void main(String[] args) {
17. }
42. // TODO Auto-generated method stub
18. }
43. Graph g= new Graph(3);
19. void addEdge(int source, int destination)
44. g.addEdge(0,1);
20. {
45. g.addEdge(1,2);
21. adjList[source].add(destination);//add()
is inbuilt method of linked list 46. g.addEdge(2,0);
22. adjList[destination].add(source); 47. g.displayGraph();
23. } 48. } 41
49. }

You might also like