-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Linked_List_Bubble_Sort.java
133 lines (111 loc) · 2.34 KB
/
Linked_List_Bubble_Sort.java
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* Author: Jennifer Tran
* Last Updated: 21/10/2016
*
* NOTE: To make this code OOP friendly, place the Node and
* LinkedList classes outside of the LinkedList_Bubble_Sort
* class and remove the static.
*/
public class Linked_List_Bubble_Sort
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
// Adding integers unordered
list.insertAtTop(14);
list.insertAtTop(33);
list.insertAtTop(27);
list.insertAtTop(35);
list.insertAtTop(10);
// Prints the integers before sorting
System.out.println("Before sorting: ");
list.print();
// Call BubbleSort method
list.bubbleSort();
System.out.println();
// Prints out the integers after sorting
System.out.println("After sorting: ");
list.print();
}
static class Node
{
private int item;
private Node next;
// Constructor
public Node (int newItem, Node newNode)
{
item = newItem;
next = newNode;
}
// Getter's and Setters
public int getItem()
{
return item;
}
public void setItem(int newItem)
{
item = newItem;
}
public Node getNext()
{
return next;
}
public void setNext(Node newNext)
{
next = newNext;
}
}
static class LinkedList
{
private Node top;
public LinkedList()
{
top = null;
}
public void insertAtTop(int value)
{
Node newNode = new Node(value,top);
top = newNode;
}
public void print()
{
Node curr = top;
while(curr != null)
{
System.out.print(curr.getItem() + " ");
curr = curr.getNext();
}
System.out.println();
}
public void bubbleSort()
{
Node curr = top;
Node prev = null;
int temp = 0;
while(curr.getNext() != null)
{
prev = top;
while(prev.getNext() != null)
{
// If previous item is greater than current
if(prev.getItem() > prev.getNext().getItem())
{
temp = prev.getItem();
// Make the swap
prev.setItem(prev.getNext().getItem());
prev.getNext().setItem(temp);
}
prev = prev.getNext();
}
curr = curr.getNext();
}
}
}
}
/*
OUTPUT:
Before sorting:
10 35 27 33 14
After sorting:
10 14 27 33 35
*/