Skip to content

Commit b09d7f5

Browse files
authored
Merge pull request #1248 from Maheshwari-Love/add/tree-sort
Tree Sort readme added in Sorting Algorithms
2 parents 7fc8222 + bef9b22 commit b09d7f5

File tree

3 files changed

+449
-152
lines changed

3 files changed

+449
-152
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
--
2+
id: Cocktail-Sort
3+
title: Cocktail Sort (Geeks for Geeks)
4+
sidebar_label: Cocktail Sort
5+
tags:
6+
- Intermediate
7+
- Sorting Algorithms
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- Java
12+
- JavaScript
13+
- DSA
14+
description: "This is a solution to the Cocktail Sort problem on Geeks for Geeks."
15+
---
16+
17+
## 1. What is Cocktail Sort?
18+
19+
Cocktail Sort is a variation of Bubble Sort. It traverses the list in both directions alternatively. This algorithm is also known as Bidirectional Bubble Sort or Shaker Sort.
20+
21+
## 2. Algorithm for Cocktail Sort
22+
23+
1. Start at the beginning of the list.
24+
2. Traverse the list from left to right, swapping adjacent items if they are in the wrong order.
25+
3. When the end of the list is reached, reverse the direction and traverse from right to left, again swapping adjacent items if they are in the wrong order.
26+
4. Repeat steps 2 and 3 until the list is sorted.
27+
28+
## 3. How does Cocktail Sort work?
29+
30+
- It sorts in both directions in each pass through the list, which can help elements move into place faster.
31+
- This bidirectional approach allows earlier elements to "bubble up" and later elements to "bubble down" in the same pass, potentially reducing the number of overall passes needed.
32+
33+
## 4. Problem Description
34+
35+
Given an array of integers, implement the Cocktail Sort algorithm to sort the array.
36+
37+
## 5. Examples
38+
39+
**Example 1:**
40+
41+
```
42+
Input: [5, 1, 4, 2, 8, 0, 2]
43+
Output: [0, 1, 2, 2, 4, 5, 8]
44+
```
45+
**Example 2:**
46+
```
47+
Input: [5, 1, 4, 2, 9, 8]
48+
Output: [1, 2, 4, 5, 8, 9]
49+
```
50+
51+
## 6. Constraints
52+
53+
- The array should contain at least one element.
54+
55+
## 7. Implementation
56+
57+
**Python**
58+
```python
59+
def cocktail_sort(arr):
60+
n = len(arr)
61+
swapped = True
62+
start = 0
63+
end = n - 1
64+
while swapped:
65+
swapped = False
66+
for i in range(start, end):
67+
if arr[i] > arr[i + 1]:
68+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
69+
swapped = True
70+
if not swapped:
71+
break
72+
swapped = False
73+
end -= 1
74+
for i in range(end - 1, start - 1, -1):
75+
if arr[i] > arr[i + 1]:
76+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
77+
swapped = True
78+
start += 1
79+
return arr
80+
```
81+
```java
82+
import java.util.Arrays;
83+
84+
public class CocktailSort {
85+
public static void cocktailSort(int[] arr) {
86+
boolean swapped = true;
87+
int start = 0;
88+
int end = arr.length - 1;
89+
90+
while (swapped) {
91+
swapped = false;
92+
for (int i = start; i < end; i++) {
93+
if (arr[i] > arr[i + 1]) {
94+
int temp = arr[i];
95+
arr[i] = arr[i + 1];
96+
arr[i + 1] = temp;
97+
swapped = true;
98+
}
99+
}
100+
if (!swapped) break;
101+
swapped = false;
102+
end--;
103+
for (int i = end - 1; i >= start; i--) {
104+
if (arr[i] > arr[i + 1]) {
105+
int temp = arr[i];
106+
arr[i] = arr[i + 1];
107+
arr[i + 1] = temp;
108+
swapped = true;
109+
}
110+
}
111+
start++;
112+
}
113+
}
114+
115+
public static void main(String[] args) {
116+
int[] arr = {5, 1, 4, 2, 8, 0, 2};
117+
cocktailSort(arr);
118+
System.out.println(Arrays.toString(arr));
119+
}
120+
}
121+
122+
```
123+
124+
## 8. Complexity Analysis
125+
126+
- **Time Complexity**:
127+
- Best case: $O(n)$ (when the array is already sorted)
128+
Average case: $O(n^2)$
129+
Worst case: $O(n^2)$
130+
131+
- **Space Complexity**: $O(1)$ (in-place sorting)
132+
133+
## 9. Advantages and Disadvantages
134+
135+
**Advantages:**
136+
- Cocktail Sort can be more efficient than Bubble Sort for certain types of input because it can address issues where small elements are initially near the end of the list.
137+
- Simple to understand and implement.
138+
139+
**Disadvantages:**
140+
- Still has a worst-case time complexity of $O(n^2)$, making it inefficient on large lists compared to more advanced algorithms like Quick Sort, Merge Sort, or Heap Sort.
141+
- The bidirectional approach does not significantly improve performance for most input cases.
142+
143+
## 10. References
144+
145+
- **GFG Article on Cocktail Sort:** [Geeks for Geeks Cocktail Sort](https://www.geeksforgeeks.org/cocktail-sort/)
146+
- **Wikipedia Article on Cocktail Sort:** [Cocktail Sort - Wikipedia](https://en.wikipedia.org/wiki/cocktail_sort)
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
--
2+
id: Tree-Sort
3+
title: Tree Sort (Geeks for Geeks)
4+
sidebar_label: Tree Sort
5+
tags:
6+
- Intermediate
7+
- Sorting Algorithms
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- Java
12+
- JavaScript
13+
- DSA
14+
description: "This is a solution to the Tree Sort problem on Geeks for Geeks."
15+
---
16+
17+
## 1. What is Tree Sort?
18+
19+
Tree Sort is a sorting algorithm that uses a Binary Search Tree (BST) to sort elements. The elements are inserted into a BST and then an in-order traversal is performed to retrieve them in sorted order.
20+
21+
## 2. Algorithm for Tree Sort
22+
23+
1. Create an empty Binary Search Tree (BST).
24+
2. Insert all elements from the array into the BST.
25+
3. Perform an in-order traversal of the BST to retrieve the elements in sorted order.
26+
27+
## 3. How does Tree Sort work?
28+
29+
- Each element from the array is inserted into a BST.
30+
- During the in-order traversal of the BST, elements are retrieved in ascending order because the left subtree is visited first, followed by the root, and then the right subtree.
31+
32+
## 4. Problem Description
33+
34+
Given an array of integers, implement the Tree Sort algorithm to sort the array.
35+
36+
## 5. Examples
37+
38+
**Example 1:**
39+
40+
```
41+
Input: [10, 7, 8, 9, 1, 5]
42+
Output: [1, 5, 7, 8, 9, 10]
43+
```
44+
45+
**Example 2:**
46+
```
47+
Input: [38, 27, 43, 3, 9, 82, 10]
48+
Output: [3, 9, 10, 27, 38, 43, 82]
49+
50+
```
51+
52+
## 6. Constraints
53+
54+
- The array should contain at least one element.
55+
56+
## 7. Implementation
57+
58+
**Python**
59+
```python
60+
class TreeNode:
61+
def __init__(self, key):
62+
self.left = None
63+
self.right = None
64+
self.val = key
65+
66+
def insert(root, key):
67+
if root is None:
68+
return TreeNode(key)
69+
else:
70+
if key < root.val:
71+
root.left = insert(root.left, key)
72+
else:
73+
root.right = insert(root.right, key)
74+
return root
75+
76+
def inorder_traversal(root, res):
77+
if root:
78+
inorder_traversal(root.left, res)
79+
res.append(root.val)
80+
inorder_traversal(root.right, res)
81+
82+
def tree_sort(arr):
83+
if not arr:
84+
return []
85+
root = TreeNode(arr[0])
86+
for key in arr[1:]:
87+
insert(root, key)
88+
sorted_array = []
89+
inorder_traversal(root, sorted_array)
90+
return sorted_array
91+
92+
```
93+
```java
94+
import java.util.*;
95+
96+
class TreeNode {
97+
int val;
98+
TreeNode left, right;
99+
TreeNode(int item) {
100+
val = item;
101+
left = right = null;
102+
}
103+
}
104+
105+
public class TreeSort {
106+
TreeNode root;
107+
108+
void insert(int key) {
109+
root = insertRec(root, key);
110+
}
111+
112+
TreeNode insertRec(TreeNode root, int key) {
113+
if (root == null) {
114+
root = new TreeNode(key);
115+
return root;
116+
}
117+
if (key < root.val) {
118+
root.left = insertRec(root.left, key);
119+
} else if (key > root.val) {
120+
root.right = insertRec(root.right, key);
121+
}
122+
return root;
123+
}
124+
125+
void inorderRec(TreeNode root, List<Integer> res) {
126+
if (root != null) {
127+
inorderRec(root.left, res);
128+
res.add(root.val);
129+
inorderRec(root.right, res);
130+
}
131+
}
132+
133+
public static List<Integer> treeSort(int[] arr) {
134+
TreeSort tree = new TreeSort();
135+
for (int num : arr) {
136+
tree.insert(num);
137+
}
138+
List<Integer> sortedArray = new ArrayList<>();
139+
tree.inorderRec(tree.root, sortedArray);
140+
return sortedArray;
141+
}
142+
143+
public static void main(String[] args) {
144+
int[] arr = {5, 1, 4, 2, 8, 0, 2};
145+
List<Integer> sortedArr = treeSort(arr);
146+
for (int num : sortedArr) {
147+
System.out.print(num + " ");
148+
}
149+
}
150+
}
151+
152+
```
153+
154+
## 8. Complexity Analysis
155+
156+
- **Time Complexity**:
157+
-Best case: $O(n \log n)$ (balanced BST)
158+
Average case: $O(n \log n)$ (balanced BST)
159+
Worst case: $O(n^2)$ (unbalanced BST)
160+
161+
- **Space Complexity**: $O(n)$ (for the BST and recursion stack)
162+
163+
## 9. Advantages and Disadvantages
164+
165+
**Advantages:**
166+
- Can achieve $O(n \log n)$ time complexity if the BST remains balanced.
167+
- Simple to understand and implement.
168+
169+
**Disadvantages:**
170+
- In the worst case (unbalanced BST), the time complexity degrades to $O(n^2)$.
171+
- Requires additional memory for the tree structure, which is $O(n)$.
172+
- The bidirectional approach does not significantly improve performance for most input cases.
173+
174+
## 10. References
175+
176+
- **GFG Article on Tree Sort:** [Geeks for Geeks Counting Sort](https://www.geeksforgeeks.org/cartesian-tree-sorting/)
177+
- **Wikipedia Article on Tree Sort:** [Counting Sort - Wikipedia](https://en.wikipedia.org/wiki/Tree_sort)

0 commit comments

Comments
 (0)