-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubble Sort On Doubly Linked List
More file actions
94 lines (81 loc) · 2.06 KB
/
Copy pathBubble Sort On Doubly Linked List
File metadata and controls
94 lines (81 loc) · 2.06 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class GFG
{
// structure of a node
static class Node
{
int data;
Node prev;
Node next;
};
// Function to insert a node at the beginning of a linked list
static Node insertAtTheBegin( Node start_ref, int data)
{
Node ptr1 = new Node();
ptr1.data = data;
ptr1.next = start_ref;
if (start_ref != null)
(start_ref).prev = ptr1;
start_ref = ptr1;
return start_ref;
}
// Function to print nodes in a given linked list
static void printList( Node start)
{
Node temp = start;
System.out.println();
while (temp != null)
{
System.out.print( temp.data + " ");
temp = temp.next;
}
}
// Bubble sort the given linked list
static Node bubbleSort( Node start)
{
int swapped, i;
Node ptr1;
Node lptr = null;
// Checking for empty list
if (start == null)
return null;
do
{
swapped = 0;
ptr1 = start;
while (ptr1.next != lptr)
{
if (ptr1.data > ptr1.next.data)
{
int t = ptr1.data;
ptr1.data = ptr1.next.data;
ptr1.next.data = t;
swapped = 1;
}
ptr1 = ptr1.next;
}
lptr = ptr1;
}
while (swapped != 0);
return start;
}
// Driver code
public static void main(String args[])
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
// start with empty linked list
Node start = null;
// Create linked list from the array arr[].
//Created linked list will be 1->11->2->56->12
for (i = 0; i < 6; i++)
start=insertAtTheBegin(start, arr[i]);
// print list before sorting
System.out.printf("\n Linked list before sorting ");
printList(start);
// sort the linked list
start = bubbleSort(start);
// print list after sorting
System.out.printf("\n Linked list after sorting ");
printList(start);
}
}