Skip to content

Tree Sort readme added in Sorting Algorithms #1248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions dsa-solutions/Sorting-Algorithms/Cocktail-Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
--
id: Cocktail-Sort
title: Cocktail Sort (Geeks for Geeks)
sidebar_label: Cocktail Sort
tags:
- Intermediate
- Sorting Algorithms
- Geeks for Geeks
- CPP
- Python
- Java
- JavaScript
- DSA
description: "This is a solution to the Cocktail Sort problem on Geeks for Geeks."
---

## 1. What is Cocktail Sort?

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.

## 2. Algorithm for Cocktail Sort

1. Start at the beginning of the list.
2. Traverse the list from left to right, swapping adjacent items if they are in the wrong order.
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.
4. Repeat steps 2 and 3 until the list is sorted.

## 3. How does Cocktail Sort work?

- It sorts in both directions in each pass through the list, which can help elements move into place faster.
- 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.

## 4. Problem Description

Given an array of integers, implement the Cocktail Sort algorithm to sort the array.

## 5. Examples

**Example 1:**

```
Input: [5, 1, 4, 2, 8, 0, 2]
Output: [0, 1, 2, 2, 4, 5, 8]
```
**Example 2:**
```
Input: [5, 1, 4, 2, 9, 8]
Output: [1, 2, 4, 5, 8, 9]
```

## 6. Constraints

- The array should contain at least one element.

## 7. Implementation

**Python**
```python
def cocktail_sort(arr):
n = len(arr)
swapped = True
start = 0
end = n - 1
while swapped:
swapped = False
for i in range(start, end):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
if not swapped:
break
swapped = False
end -= 1
for i in range(end - 1, start - 1, -1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
start += 1
return arr
```
```java
import java.util.Arrays;

public class CocktailSort {
public static void cocktailSort(int[] arr) {
boolean swapped = true;
int start = 0;
int end = arr.length - 1;

while (swapped) {
swapped = false;
for (int i = start; i < end; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
swapped = false;
end--;
for (int i = end - 1; i >= start; i--) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
start++;
}
}

public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8, 0, 2};
cocktailSort(arr);
System.out.println(Arrays.toString(arr));
}
}

```

## 8. Complexity Analysis

- **Time Complexity**:
- Best case: $O(n)$ (when the array is already sorted)
Average case: $O(n^2)$
Worst case: $O(n^2)$

- **Space Complexity**: $O(1)$ (in-place sorting)

## 9. Advantages and Disadvantages

**Advantages:**
- 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.
- Simple to understand and implement.

**Disadvantages:**
- 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.
- The bidirectional approach does not significantly improve performance for most input cases.

## 10. References

- **GFG Article on Cocktail Sort:** [Geeks for Geeks Cocktail Sort](https://www.geeksforgeeks.org/cocktail-sort/)
- **Wikipedia Article on Cocktail Sort:** [Cocktail Sort - Wikipedia](https://en.wikipedia.org/wiki/cocktail_sort)
177 changes: 177 additions & 0 deletions dsa-solutions/Sorting-Algorithms/Tree-Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
--
id: Tree-Sort
title: Tree Sort (Geeks for Geeks)
sidebar_label: Tree Sort
tags:
- Intermediate
- Sorting Algorithms
- Geeks for Geeks
- CPP
- Python
- Java
- JavaScript
- DSA
description: "This is a solution to the Tree Sort problem on Geeks for Geeks."
---

## 1. What is Tree Sort?

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.

## 2. Algorithm for Tree Sort

1. Create an empty Binary Search Tree (BST).
2. Insert all elements from the array into the BST.
3. Perform an in-order traversal of the BST to retrieve the elements in sorted order.

## 3. How does Tree Sort work?

- Each element from the array is inserted into a BST.
- 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.

## 4. Problem Description

Given an array of integers, implement the Tree Sort algorithm to sort the array.

## 5. Examples

**Example 1:**

```
Input: [10, 7, 8, 9, 1, 5]
Output: [1, 5, 7, 8, 9, 10]
```

**Example 2:**
```
Input: [38, 27, 43, 3, 9, 82, 10]
Output: [3, 9, 10, 27, 38, 43, 82]

```

## 6. Constraints

- The array should contain at least one element.

## 7. Implementation

**Python**
```python
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

def insert(root, key):
if root is None:
return TreeNode(key)
else:
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root

def inorder_traversal(root, res):
if root:
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)

def tree_sort(arr):
if not arr:
return []
root = TreeNode(arr[0])
for key in arr[1:]:
insert(root, key)
sorted_array = []
inorder_traversal(root, sorted_array)
return sorted_array

```
```java
import java.util.*;

class TreeNode {
int val;
TreeNode left, right;
TreeNode(int item) {
val = item;
left = right = null;
}
}

public class TreeSort {
TreeNode root;

void insert(int key) {
root = insertRec(root, key);
}

TreeNode insertRec(TreeNode root, int key) {
if (root == null) {
root = new TreeNode(key);
return root;
}
if (key < root.val) {
root.left = insertRec(root.left, key);
} else if (key > root.val) {
root.right = insertRec(root.right, key);
}
return root;
}

void inorderRec(TreeNode root, List<Integer> res) {
if (root != null) {
inorderRec(root.left, res);
res.add(root.val);
inorderRec(root.right, res);
}
}

public static List<Integer> treeSort(int[] arr) {
TreeSort tree = new TreeSort();
for (int num : arr) {
tree.insert(num);
}
List<Integer> sortedArray = new ArrayList<>();
tree.inorderRec(tree.root, sortedArray);
return sortedArray;
}

public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8, 0, 2};
List<Integer> sortedArr = treeSort(arr);
for (int num : sortedArr) {
System.out.print(num + " ");
}
}
}

```

## 8. Complexity Analysis

- **Time Complexity**:
-Best case: $O(n \log n)$ (balanced BST)
Average case: $O(n \log n)$ (balanced BST)
Worst case: $O(n^2)$ (unbalanced BST)

- **Space Complexity**: $O(n)$ (for the BST and recursion stack)

## 9. Advantages and Disadvantages

**Advantages:**
- Can achieve $O(n \log n)$ time complexity if the BST remains balanced.
- Simple to understand and implement.

**Disadvantages:**
- In the worst case (unbalanced BST), the time complexity degrades to $O(n^2)$.
- Requires additional memory for the tree structure, which is $O(n)$.
- The bidirectional approach does not significantly improve performance for most input cases.

## 10. References

- **GFG Article on Tree Sort:** [Geeks for Geeks Counting Sort](https://www.geeksforgeeks.org/cartesian-tree-sorting/)
- **Wikipedia Article on Tree Sort:** [Counting Sort - Wikipedia](https://en.wikipedia.org/wiki/Tree_sort)
Loading
Loading