트리 정렬 을 기반으로 하는 정렬 알고리즘입니다. 이진 검색 트리 데이터 구조. 먼저 입력 목록이나 배열의 요소에서 이진 검색 트리를 생성한 다음 생성된 이진 검색 트리에서 순차 순회를 수행하여 정렬된 순서로 요소를 가져옵니다.
연산:
1단계: 배열의 요소 입력을 가져옵니다.2단계: 배열의 데이터 항목을 배열에 삽입하여 이진 검색 트리를 만듭니다. 이진 검색 트리 .3단계: 정렬된 순서로 요소를 가져오려면 트리에서 순차 순회를 수행합니다.트리 정렬의 응용:
- 가장 일반적인 용도는 온라인으로 요소를 편집하는 것입니다. 각 설치 후 지금까지 본 개체 세트를 구조화된 프로그램에서 사용할 수 있습니다.
- 스플레이 트리를 이진 검색 트리로 사용하는 경우 결과 알고리즘(splaysort라고 함)에는 적응형 정렬이라는 추가 속성이 있습니다. 즉, 가상 입력에 대한 작업 시간이 O(n log n)보다 빠릅니다.
다음은 위의 접근 방식을 구현한 것입니다.
C++Java// C++ program to implement Tree Sort #includeusing namespace std; struct Node { int key; struct Node *left *right; }; // A utility function to create a new BST Node struct Node *newNode(int item) { struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } // Stores inorder traversal of the BST // in arr[] void storeSorted(Node *root int arr[] int &i) { if (root != NULL) { storeSorted(root->left arr i); arr[i++] = root->key; storeSorted(root->right arr i); } } /* A utility function to insert a new Node with given key in BST */ Node* insert(Node* node int key) { /* If the tree is empty return a new Node */ if (node == NULL) return newNode(key); /* Otherwise recur down the tree */ if (key < node->key) node->left = insert(node->left key); else if (key > node->key) node->right = insert(node->right key); /* return the (unchanged) Node pointer */ return node; } // This function sorts arr[0..n-1] using Tree Sort void treeSort(int arr[] int n) { struct Node *root = NULL; // Construct the BST root = insert(root arr[0]); for (int i=1; i<n; i++) root = insert(root arr[i]); // Store inorder traversal of the BST // in arr[] int i = 0; storeSorted(root arr i); } // Driver Program to test above functions int main() { //create input array int arr[] = {5 4 7 2 11}; int n = sizeof(arr)/sizeof(arr[0]); treeSort(arr n); for (int i=0; i<n; i++) cout << arr[i] << ' '; return 0; } Python3// Java program to // implement Tree Sort class GFG { // Class containing left and // right child of current // node and key value class Node { int key; Node left right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root int key) { /* If the tree is empty return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise recur down the tree */ if (key < root.key) root.left = insertRec(root.left key); else if (key > root.key) root.right = insertRec(root.right key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + ' '); inorderRec(root.right); } } void treeins(int arr[]) { for(int i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code public static void main(String[] args) { GFG tree = new GFG(); int arr[] = {5 4 7 2 11}; tree.treeins(arr); tree.inorderRec(tree.root); } } // This code is contributed // by Vibin MC## Python3 program to # implement Tree Sort # Class containing left and # right child of current # node and key value class Node: def __init__(selfitem = 0): self.key = item self.leftself.right = NoneNone # Root of BST root = Node() root = None # This method mainly # calls insertRec() def insert(key): global root root = insertRec(root key) # A recursive function to # insert a new key in BST def insertRec(root key): # If the tree is empty # return a new node if (root == None): root = Node(key) return root # Otherwise recur # down the tree if (key < root.key): root.left = insertRec(root.left key) elif (key > root.key): root.right = insertRec(root.right key) # return the root return root # A function to do # inorder traversal of BST def inorderRec(root): if (root != None): inorderRec(root.left) print(root.key end = ' ') inorderRec(root.right) def treeins(arr): for i in range(len(arr)): insert(arr[i]) # Driver Code arr = [5 4 7 2 11] treeins(arr) inorderRec(root) # This code is contributed by shinjanpatraJavaScript// C# program to // implement Tree Sort using System; public class GFG { // Class containing left and // right child of current // node and key value public class Node { public int key; public Node left right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root int key) { /* If the tree is empty return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise recur down the tree */ if (key < root.key) root.left = insertRec(root.left key); else if (key > root.key) root.right = insertRec(root.right key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + ' '); inorderRec(root.right); } } void treeins(int []arr) { for(int i = 0; i < arr.Length; i++) { insert(arr[i]); } } // Driver Code public static void Main(String[] args) { GFG tree = new GFG(); int []arr = {5 4 7 2 11}; tree.treeins(arr); tree.inorderRec(tree.root); } } // This code is contributed by Rajput-Ji<script> // Javascript program to // implement Tree Sort // Class containing left and // right child of current // node and key value class Node { constructor(item) { this.key = item; this.left = this.right = null; } } // Root of BST let root = new Node(); root = null; // This method mainly // calls insertRec() function insert(key) { root = insertRec(root key); } /* A recursive function to insert a new key in BST */ function insertRec(root key) { /* If the tree is empty return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise recur down the tree */ if (key < root.key) root.left = insertRec(root.left key); else if (key > root.key) root.right = insertRec(root.right key); /* return the root */ return root; } // A function to do // inorder traversal of BST function inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key + ' '); inorderRec(root.right); } } function treeins(arr) { for (let i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code let arr = [5 4 7 2 11]; treeins(arr); inorderRec(root); // This code is contributed // by Saurabh Jaiswal </script>
산출2 4 5 7 11복잡성 분석:
평균 사례 시간 복잡성: O(n log n) 이진 검색 트리에 하나의 항목을 추가하는 데 평균 O(log n) 시간이 걸립니다. 따라서 n개의 항목을 추가하는 데는 O(n log n) 시간이 걸립니다.
최악의 경우 시간 복잡도: 에2). Red Black Tree AVL Tree와 같은 자체 균형 이진 검색 트리를 사용하면 Tree Sort의 최악의 시간 복잡도를 개선할 수 있습니다. 자체 균형 이진 트리 트리 정렬을 사용하면 최악의 경우 배열을 정렬하는 데 O(n log n) 시간이 걸립니다.
보조 공간: 에)