Skip to content

Commit ad1e6dd

Browse files
authored
Update Bubble Sort (Iterative) Linked List
1 parent a93f192 commit ad1e6dd

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 8 - Linked Lists II/Bubble Sort (Iterative) Linked List

+64
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,67 @@ Sample Input 2 :
3030
Sample Output 2 :
3131
-5 1 5 9 10 67 89 90
3232
*/
33+
34+
/*
35+
36+
Following is the Node class already written for the Linked List
37+
38+
class LinkedListNode<T> {
39+
T data;
40+
LinkedListNode<T> next;
41+
42+
public LinkedListNode(T data) {
43+
this.data = data;
44+
}
45+
}
46+
47+
*/
48+
49+
50+
public class Solution {
51+
52+
public static int findLengthLL(LinkedListNode<Integer> head)
53+
{
54+
int count=0;
55+
while(head.next!=null)
56+
{
57+
head=head.next;
58+
count=count+1;
59+
}
60+
return count;
61+
62+
}
63+
64+
public static LinkedListNode<Integer> bubbleSort(LinkedListNode<Integer> head) {
65+
//Your code goes here
66+
if (head==null || head.next==null)
67+
{
68+
return head;
69+
}
70+
int n=findLengthLL(head);
71+
LinkedListNode<Integer> node1=null,node2=null,temp=null;
72+
int data1=0,data2=0;
73+
for (int i=0;i<n;i++)
74+
{
75+
node1=head;
76+
node2=head.next;
77+
for (int j=0;j<n-i;j++)
78+
{
79+
data1=node1.data;
80+
data2=node2.data;
81+
if (data1>data2)
82+
{
83+
node1.data=data2;
84+
node2.data=data1;
85+
}
86+
node1=node1.next;
87+
node2=node2.next;
88+
89+
}
90+
//Runner.print(head);
91+
}
92+
//System.out.println();
93+
return head;
94+
95+
}
96+
}

0 commit comments

Comments
 (0)