-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathBubble Sort (Iterative) LinkedList
More file actions
55 lines (40 loc) · 1.48 KB
/
Bubble Sort (Iterative) LinkedList
File metadata and controls
55 lines (40 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Bubble Sort (Iterative) LinkedList
// Send Feedback
// Sort a given linked list using Bubble Sort (iteratively). While sorting, you need to swap just the data.
// You don't need to print the elements, just sort the elements and return the head of updated LL.
// Input format : Linked list elements (separated by space and terminated by -1)`
// Sample Input 1 :
// 1 4 5 2 -1
// Sample Output 1 :
// 1 2 4 5
public class Solution {
public static LinkedListNode<Integer> bubbleSort(LinkedListNode<Integer> head )
{
//Write your code here
LinkedListNode<Integer> current = head, index = null;
int temp;
if(head == null) {
return head;
}
else
{
while(current != null)
{
//Node index will point to node next to current
index = current.next;
while(index != null)
{
//If current node's data is greater than index's node data, swap the data between them
if(current.data > index.data)
{
temp = current.data;
current.data = index.data;
index.data = temp;
}
index = index.next;
}
current = current.next;
}
} return head;
}
}