You are reading the article Python Program To Sort The Elements Of The Circular Linked List updated in December 2023 on the website Bellydancehcm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Python Program To Sort The Elements Of The Circular Linked List
When it is required to sort the elements of a circular linked list, a ‘Node’ class needs to be created. In this class, there are two attributes, the data that is present in the node, and the access to the next node of the linked list.
In a circular linked list, the head and the rear are adjacent to each other. They are connected to form a circle, and don’t have ‘NULL’ value in the last node.
Another ‘linked_list’ class needs to be created that would have an initialization function, and the head of the node would be initialized to ‘None’.
Multiple methods are defined by the user to add node to the linked list, sort the linked list in ascending or descending order and to print the node values.
Below is a demonstration for the same −
ExampleLive Demo
class Node: def __init__(self,data): chúng tôi = data chúng tôi = None class list_creation: def __init__(self): chúng tôi = Node(None) chúng tôi = Node(None) chúng tôi = self.tail chúng tôi = self.head def add_data(self,my_data): new_node = Node(my_data) if chúng tôi is None: self.head = new_node self.tail = new_node new_node.next = self.head else: self.tail.next = new_node self.tail = new_node self.tail.next = self.head def sort_list(self): curr = self.head if(self.head == None): print("The list is empty") else: while(True): index_val = curr.next while(index_val != self.head): temp = curr.data chúng tôi = index_val.data index_val.data = temp index_val = index_val.next curr =curr.next if(curr.next == self.head): break; def print_it(self): curr = self.head if chúng tôi is None: print("The list is empty"); return; else: print(curr.data) while(curr.next != self.head): curr = curr.next print(curr.data) print("n") class circular_linked_list: my_cl = list_creation() print("Nodes are being added to the list") my_cl.add_data(21) my_cl.add_data(54) my_cl.add_data(78) my_cl.add_data(99) my_cl.add_data(27) print("The list is :") my_cl.print_it() print("The list is being sorted") my_cl.sort_list() print("The sorted list is : ") my_cl.print_it() Output Nodes are being added to the list The list is : 21 54 78 99 27 The list is being sorted The sorted list is : 21 27 54 78 99 Explanation
The ‘Node’ class is created.
Another class with required attributes is created.
Another method named ‘sort_list’ is defined, that is used to sort the elements in the circular linked list in an ascending or descending order.
Another method named ‘print_it’ is defined, that displays the nodes of the circular linked list.
An object of the ‘list_creation’ class is created, and the methods are called on it to add data.
An ‘init’ method is defined, that the first and last nodes of the circular linked list to None.
The ‘sort_list’ method is called.
It iterates through the list, and places the elements in their relevant position based on the value.
This is displayed on the console using the ‘print_it’ method.
You're reading Python Program To Sort The Elements Of The Circular Linked List
Python Program To Split A List Into Two Halves
In Python, a single variable can contain multiple items by using lists. One of the four builtin data types for storing data collections in Python is a list; the other three are tuples, sets and dictionaries, each with its own purpose.
What Is List?Square brackets are used to build chúng tôi most effective tool in Python is the list because they don’t necessarily have to be homogeneous. DataTypes like Integers, Strings, and Objects can all be found in one list. Because lists are mutable, changes can be made to them even after they have been created.
In this article, we will explore various methods for dividing a list into halves using Python programming. Lists are one of the mutable data types that can store a collection of objects. With these techniques, you will be able to divide any list in half with ease!
Using The Slicing TechniqueIn the first scenario, the list is divided in half or two halves. Depending on the length of the list, these halves can be either equal or uneven in size. The list can be split up using the slicing method.
Algorithm
Create a list and initialize its mid index using half of its length.
Split it in two halves from the start to mid-index and from mid-index till end respectively.
Print out both original list, as well as each split half.
Sort each of these halves before merging them together into a single, sorted list.
Finally, print out this new merged, sorted list.
ExampleThe following example creates a list with 6 elements, then sets the index to 3. It then splits the list into two halves based on that index – the first half is all of the elements before the index, and second half is all of the elements after it. Finally, it prints out both halves of the list.
#create list list_1 = [10,20,30,40,50,60] index = 3 first_half = list_1 [:index] second_half = list_1 [index:] print('The primary list is: ',list_1) print("First half of list is ",first_half) print("Second half of list is ",second_half) Output The primary list is: [10, 20, 30, 40, 50, 60] First half of list is [10, 20, 30] Second half of list is [40, 50, 60]Here, in the method explained above we had the index and the length of the list was predefined. What if the dividing index or the size of the two parts are not specified? The next step is to determine the list’s middle index, which may be done by multiplying the list’s length by 2. However, if the list’s length is an odd integer or the list is not symmetrical, we will obtain a float value when we divide the list. To round the result, we will use the floor operator (//).
ExampleIn this method, our main focus is on solving a different condition that is, if the elements asked from the user is odd in number, then what will be the process of completing the task. Here, the split function returns two unequal lists since the list has an odd number of elements. The midway is (5/2) = 2.5 because the list is 5 items long. The closest integer value that is less than or equal to a division result is returned by the floor operator. The floor operator in this instance yields 2 rather than 2.5.
Algorithm
Define a function that takes in a list of numbers and asks the user for an input value.
Use a for loop to iterate through the list,
Then use the append() function to divide each number by 2 and find its middle index.
Prompt the user for their input when complete.
The following example shows that the program takes a list of numbers as input from the user and splits it into two halves. It asks the user to enter the number of elements they want in their list and then prompts them to enter each element one at a time.
The middle index is calculated by dividing the length of the list by 2, then using this index it calls split_list() which uses slicing to separate the first half and second half of the list and returns both lists separately.
def split_list(input_L,n): first_half = input_L[:n] second_half = input_L[n:] return first_half,second_half if __name__ == "__main__" : list_1 = [] length = int(input("Enter the number of elements you want in list : ")) for i in range(0, length): item = int(input("Enter the element for list "+str(i+1)+" :")) list_1.append (item) middle_index = length//2 first,second = split_list (list_1,middle_index) print ("Primary list: ", list_1) print ("First half of the list is: ", first) print ("second half of the list is: ", second) OutputOn executing the above program, the following output is generated −
Enter the number of elements you want in list: 5 Enter the element for list 1:98 Enter the element for list 2:60 Enter the element for list 3:45 Enter the element for list 4:33 Enter the element for list 5:55 Primary list: [98, 60, 45, 33, 55] First half of the list is: [98, 60] second half of the list is: [45, 33, 55] ConclusionIn this article, we have used different ways of splitting the list into two halves using python.
Topological Sort: Python, C++ Algorithm Example
What is Topological Sort Algorithm?
Topological Sorting is also known as Kahn’s algorithm and is a popular Sorting Algorithm. Using a directed graph as input, Topological Sort sorts the nodes so that each appears before the one it points to.
This algorithm is applied on a DAG (Directed Acyclic Graph) so that each node appears in the ordered array before all other nodes are pointed to it. This algorithm follows some rules repeatedly until the sort is completed.
To simplify, look at the following example:
Directed Graph
Here, we can see that “A” has no indegree. It means the edge that points to a node. “B” and “C” have a pre-requisite of “A”, then “E” has a pre-requisite of “D” and “F” nodes. Some of the nodes are dependent on other nodes.
Here’s another representation of the above Graph:
Dependency of each node (Linear Ordering)
So, when we pass the DAG (Directed Acyclic Graph) to the topological sort, it will give us an array with linear ordering, where the first element has no dependency.
This example shows a graph with a cycle:
Here’re the steps to do this:
Step 1) Find the node with zero incoming edges, a node with zero degrees.
Step 2) Store that zeroes in-degree node in a Queue or Stack and removes the node from the Graph.
Step 3) Then delete the outgoing edge from that node.
This will decrement the in-degree count for the next node.
Topological ordering requires that the graph data structure will not have any cycle.
A graph will be considered a DAG if it follows these requirements:
One or more nodes with an indegree value of zero.
Graph doesn’t contain any cycle
As long as there’re nodes in the Graph and the Graph is still DAG, we will run the above three steps. Otherwise, the algorithm will fall into the cyclic dependency, and Kahn’s Algorithm won’t be able to find a node with zero in-degree.
How Topological Sort WorksHere, we will use “Kahn’s Algorithm” for the topological sort. Let’s say we have the following Graph:
Here’re the steps for Kahn’s Algorithm:
Step 1) Calculate the indegree or incoming edge of all nodes in the Graph.
Note:
Indegree means the directed edges pointing to the node.
Outdegree means the directed edges that come from a node.
Here’s the indegree and outdegree of the above Graph:
Step 2) Find the node with zero indegrees or zero incoming edges.
The node with zero indegree means no edges are coming toward that node. Node “A” has zero indegrees, meaning there’s no edge pointing to node “A”.
So, we will do the following actions:
Remove this node and its outdegree edges (outgoing edges)
Place the node in the Queue for ordering.
Update the in-degree count of the neighbor node of “A.”
Step 3) We need to find a node with an indegree value of zero. In this example, “B” and “C” have zero indegree.
Here, we can take either of these two. Let’s take “B” and delete it from the Graph.
Then update the indegree values of other nodes.
After performing these operations, our Graph and Queue will look like the following:
Step 4) Node “C” has no incoming edge. So, we will remove node “C” from the Graph and push it into the Queue.
We can also delete the edge that is outgoing from “C”.
Now, our Graph will look like this:
Step 5) We can see that nodes “D” and “F” have the indegree of zero. We will take a node and put it in the Queue.
Let’s take out “D” first. Then the indegree count for node “E” will be 1. Now, there’ll be no node from D to E.
We need to do the same for node “F”, our result will be like the following:
Step 6) The indegree (ingoing edges) and outdegree (outgoing edges) of node “E” became zero. So, we have met all the pre-requisite for node “E”.
Here, we l put “E” at the end of the Queue. So, we don’t have any nodes left, so the algorithm ends here.
Pseudo Code for Topological SortingHere’s the pseudo-code for the topological sort while using Kahn’s Algorithm.
function TopologicalSort( Graph G ): for each node in G: calculate the indegree start = Node with 0 indegree G.remove(start) topological_list = [start] While node with O indegree present: topological_list.append(node) G.remove(node) Update Indegree of present nodes Return topological_listTopological sort can also be implemented using the DFS (Depth First Search) method. However, that approach is the recursive method. Kahn’s algorithm is more efficient than the DFS approach.
C++ Implementation of Topological Sortingusing namespace std; class graph{ int vertices; public: graph(int vertices){ } void createEdge(int u, int v){ adjecentList[u].push_back(v); } void TopologicalSort(){
for(int i=0;i<vertices;i++){ for(itr=adjecentList[i].begin(); itr!=adjecentList[i].end();itr++){ indegree_count[*itr]++; } } for(int i=0; i<vertices;i++){ if(indegree_count[i]==0){ Q.push(i); } } int visited_node = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); order.push_back(u);
for(itr=adjecentList[u].begin(); itr!=adjecentList[u].end();itr++){ if(–indegree_count[*itr]==0){ Q.push(*itr); } } visited_node++; } if(visited_node!=vertices){ cout<<“There’s a cycle present in the Graph.nGiven graph is not DAG”<<endl; return; } for(int i=0; i<order.size();i++){ cout<<order[i]<<“t”; } } }; int main(){ graph G(6); G.createEdge(0,1); G.createEdge(0,2); G.createEdge(1,3); G.createEdge(1,5); G.createEdge(2,3); G.createEdge(2,5); G.createEdge(3,4); G.createEdge(5,4); G.TopologicalSort(); }
Output: 0 1 2 3 5 4 Python Implementation of Topological Sorting from collections import defaultdict class graph: def __init__(self, vertices): self.adjacencyList = defaultdict(list) self.Vertices = vertices # No. of vertices # function to add an edge to adjacencyList def createEdge(self, u, v): self.adjacencyList[u].append(v) # The function to do Topological Sort. def topologicalSort(self): total_indegree = [0]*(self.Vertices) for i in self.adjacencyList: for j in self.adjacencyList[i]: total_indegree[j] += 1 queue = [] for i in range(self.Vertices): if total_indegree[i] == 0: queue.append(i) visited_node = 0 order = [] while queue: u = queue.pop(0) order.append(u) for i in self.adjacencyList[u]: total_indegree[i] -= 1 if total_indegree[i] == 0: queue.append(i) visited_node += 1 if visited_node != self.Vertices: print("There's a cycle present in the Graph.nGiven graph is not DAG") else: print(order) G = graph(6) G.createEdge(0,1) G.createEdge(0,2) G.createEdge(1,3) G.createEdge(1,5) G.createEdge(2,3) G.createEdge(2,5) G.createEdge(3,4) G.createEdge(5,4) G.topologicalSort() Output: [0, 1, 2, 3, 5, 4] Cyclic Graphs of Topological Sort AlgorithmA graph containing a cycle can’t be topologically ordered. As the cyclic Graph has the dependency in a cyclic manner.
For example, check this Graph:
This Graph is not DAG (Directed Acyclic Graph) because A, B, and C create a cycle. If you notice, there’s no node with zero in-degree value.
According to Kahn’s Algorithm, if we analyze the above Graph:
Find a node with zero indegrees (no incoming edges).
However, in the above Graph, there’s no node with zero in degrees. Every node has an in-degree value greater than 0.
Return an empty queue, as it could not find any node with zero in degrees.
We can detect cycles using the topological ordering with the following steps:
Step 1) Perform topological Sorting.
Step 2) Calculate the total number of elements in the topologically sorted list.
Step 3) If the number of elements equals the total number of vertex, then there’s no cycle.
Step 4) If it’s not equal to the number of vertices, then there’s at least one cycle in the given graph data structure.
Complexity Analysis of Topological SortThere are two types of complexity in algorithms. They’re
Time Complexity
Space Complexity
These complexities are represented with a function that provides a general complexity.
Time Complexity: All time complexity is the same for Topological Sorting. There are worst, average, and best-case scenarios for time complexity.
The time complexity for topological Sorting is O(E + V), here, E means the number of Edges in the Graph, and V means the number of vertices in the Graph.
Let’s break through this complexity:
Step 1) At the beginning, we will calculate all the indegrees. To do that, we need to go through all the edges, and initially, we will assign all V vertex indegrees to zero. So, the incremental steps we complete will be O(V+E).
Step 2) We will find the node with zero indegree value. We need to search from the V number of the vertex. So, the steps completed will be O(V).
Step 3) For each node with zero indegrees, we will remove that node and decrement the indegree. Performing this operation for all the nodes will take O(E).
Step 4) Finally, we will check if there is any cycle or not. We will check whether the total number of elements in the sorted array is equal to the total number of nodes. It will take O(1).
So, these were the individual time complexity for each step of the topological Sorting or topological ordering. We can say that the time complexity from the above calculation will be O( V + E ); here, O means the complexity function.
Space Complexity: We needed O(V) spaces for running the topological sorting algorithm.
Here are the steps where we needed the space for the program:
We had to calculate all the indegrees of nodes present in the Graph. As the Graph has a total of V nodes, we need to create an array of size V. So, the space required was O(V).
A Queue data structure was used to store the node with zero indegree. We removed the nodes with zero indegree from the original Graph and placed them in the Queue. For this, the required space was O(V).
The array is named “order.” That stored the nodes in topological order. That also required O(V) spaces.
These were the individual space complexity. So, we need to maximize these spaces in the run time.
Space complexity stands for O(V), where V means the number of the vertex in the Graph.
Application of Topological SortThere’s a huge use for Topological Sorting. Here are some of them:
It is used when Operating system needs to perform the resource allocation.
Finding a cycle in the Graph. We can validate if the Graph is DAG or not with topological sort.
Sentence ordering in the auto-completion apps.
It is use for detecting deadlocks.
Different type of Scheduling or course scheduling uses the topological sort.
Resolving dependencies. For example, if you try to install a package, that package might also need other packages. Topological ordering finds out all the necessary packages to install the current package.
Linux uses the topological sort in the “apt” to check the dependency of the packages.
Python Program To Read First N Lines Of A File
In this article, we will show you how to read and print the first N lines of a text file for the given N value using python.
Assume we have taken a text file with the name chúng tôi consisting of some random text. We will return the first N lines of a text file for the given N value.
chúng tôi
Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with a joy Algorithm (Steps)Following are the Algorithm/steps to be followed to perform the desired task −
Create a variable to store the path of the text file.
Enter the N value static/dynamic for printing the first N lines of a file.
Use the open() function (opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).
with open(inputFile, 'r') as filedata:
Using the readlines() function (returns a list with each line in the file represented as a list item. To limit the number of lines returned, use the hint argument. No more lines are returned if the total amount of bytes returned exceeds the specified number) to obtain the list of lines of a given input text file.
file.readlines(hint)
Traverse in the list of lines to retrieve the first N lines of a text file using slicing (Using the slice syntax, you can return a range of characters. To return a part of the string, specify the start and end indexes, separated by a colon). Here linesList[:N] indicates all the lines till N (excluding the last Nth line since the index starts from 0) from the starting.
for textline in (linesList[:N]):
Print the first N lines of the file line by line.
Close the input file with the close() function (used to close an opened file).
ExampleThe following program prints the first N lines of a text file for the given N value −
inputFile
=
"ExampleTextFile.txt"
N=
int
(
input
(
"Enter N value: "
)
)
with
open
(
inputFile,
'r'
)
as
filedata:
linesList=
filedata.
readlines(
)
(
"The following are the first"
,
N,
"lines of a text file:"
)
for
textlinein
(
linesList[
:
N]
)
:
(
textline,
end=
''
)
filedata.
close(
)
OutputOn executing, the above program will generate the following output −
Enter N value: 4 The following are the first 4 lines of a text file: Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviatedWe took the value of N from the user (dynamic Input) and then gave our program a text file containing some random content and then opened it in reading mode. The readlines() function was then used to retrieve a list of all the lines in the file. We traversed the first N lines of the file using the for loop and slicing and printed them.
ConclusionSo, from this article, we learned how to open a file and read lines from it, which can be used to execute operations such as finding the number of words in a line, the length of a line, and so on, and we also learned slicing to access the elements from the start or end in a simple way.
C++ Program To Find The Hyperbolic Arccosine Of The Given Value
Similar to regular trigonometric functions, hyperbolic functions are defined using the hyperbola rather than the circle. From the specified radian angle, it returns the ratio parameter in the hyperbolic cosine function. But, to put it another way, to do the opposite. Inverse hyperbolic trigonometric operations like the hyperbolic arccosine operation are needed to determine the angle from the hyperbolic-cosine value.
To calculate the angle using the hyperbolic cosine value, in radians, this tutorial will show how to use the C++ hyperbolic inverse-cosine (acosh) function. The formula for the hyperbolic inverse-cosine operation is as follows −
$$mathrm{cosh^{-1}x:=:In(x:+:sqrt{x^2:-:1})},where :In: is: natural: logarithm:(log_e : k)$$
The acosh() functionUsing the acosh() function, the angle may be determined from the hyperbolic cosine value. The C++ standard library includes this function. Before using this function, the cmath library must be imported. This method accepts a hyperbolic cosine value as an input and returns the angle in radians. Simple syntax is used in the following −
SyntaxThe input range for this function is 1 and above. If the input is negative, it will raise domain error. It returns a number in range [0, +∞] (both included).
Algorithm
Take hyperbolic cosine value x as input
Use acosh( x ) to calculate the cosh−1(x)
Return result.
Exampleusing
namespace
std
;
float
solve
(
float
x
)
{
float
answer
;
answer
=
acosh
(
x
)
;
return
answer
;
}
int
main
(
)
{
float
angle
,
ang_deg
;
angle
=
solve
(
2.50918
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given hyperbolic cosine value 2.50918 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
11.5919
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given hyperbolic cosine value 11.5919 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
1.32461
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given hyperbolic cosine value 1.32461 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
1.60028
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given hyperbolic cosine value 1.60028 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
}
Output The angle (in radian) for given hyperbolic cosine value 2.50918 is: 1.5708 = 90.0001 (in degrees) The angle (in radian) for given hyperbolic cosine value 11.5919 is: 3.14159 = 180 (in degrees) The angle (in radian) for given hyperbolic cosine value 1.32461 is: 0.785399 = 45.0001 (in degrees) The angle (in radian) for given hyperbolic cosine value 1.60028 is: 1.04719 = 59.9997 (in degrees)The hyperbolic cosine value is passed to the acosh() method, which returns the angle in radian format. Using the algorithm below, we changed this output from radians to degrees.
$$mathrm{theta_{deg}:=:theta_{rad}:timesfrac{180}{pi}}$$
ConclusionWe employ the acosh() function from the cmath package to perform the inverse hyperbolic operation using the hyperbolic cosine value. This function outputs the desired angle in radians from the input value of the hyperbolic cosine. The range of the return is 0 to positive infinity. The domain error is raised when the input value is less than 1. The return type in earlier iterations of C and C++ was double; later iterations of C++ also used the overloaded form for float and long-double. When an integer value is supplied as an argument, the acosh() function will be called after casting the input parameter into the double type.
Python Program To Count Inversions Of Size Three In A Given Array
Inversion count is a step counting method by which we can calculate the number of sorting steps taken by a particular array. It is also capable to count the operation time span for an array. But, if we want to sort an array in a reverse manner, the count will be maximum number present in that array.
Array: { 5, 4, 3, 2, 1} Pairs: {5, 4}, {5,3} , {3,2}, {3,1}, {2,1},{4,3}, {4,2}, {4,1},}, {5,2}, {5,1} Output: 10 Array: {1, 2, 3, 4, 5} Pairs: No Pairs Output: 0 Array: {1,5,2,8,3,4} Pairs: {5, 2}, {5, 3}, {5, 4}, {8, 3}, {8, 4} Output: 5The inversion count indicates that how far that particular array is from being sorted in an increasing order. Here are two particular process to describe this situation attached with a solution −
To find the smaller elements: To find out the smaller element from an array, we need to iterate the index from n-1 to 0. By applying (a[i]-1), we can calculate the getSum() here. The process will run until it reach to a[i]-1.
To find the greater number: To find the greater number from an index we need to perform iteration 0 to n-1. For the every element we need to do calculation for every number till a[i]. Subtract it from i. Then we will get a the number which is greater than a[i].
Algorithm to count inversions of size three in an arrayHere in this algorithm; we learn how to count inversions of size three in a given array in a particular programming environment.
Step 1 − Start
Step 3 − Inner loop y=x+1 to N
Step 4 − If element at x is greater than element at y index
Step 5 − Then, increase the invCount++
Step 6 − Print the pair
Step 7 − Terminate
Syntax to count inversions of size three in an array:-C++ Implementation
int getInversions(int * A, int n) { int count = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { ++count; } } } return count; }Java Implementation
public static int getInversions(int[] A, int n) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { count += 1; } } } return count; }Python Implementation
def getInversions(A, n): count = 0 for i in range(n): for j in range(i + 1, n): count += 1 return count;Here we have mentioned the possible syntaxes to count inversions of size three in a given array. And for this method; Time Complexity is O(N^2), where N is the total size of the array and; Space Complexity:O(1), as no extra space has been used.
Approaches to follow
Approach 1 − Count Inversions of size three in a given array by program to count inversions of size 3
Approach 2 − Better Approach to count inversions of size 3
Approach 3 − Count inversions of size 3 using binary indexed tree
Count Inversions of size three in a given array by program to count inversions of size 3For the simple approach to count inversions of size three, we need to run a loop for all possible value of i, j and k. The time complexity is O(n^3) and O(1) reflects the auxiliary space.
The condition is −
Example 1 def getInvCount(arr): n = len(arr) invcount = 0 for i in range(0,n-1): for j in range(i+1 , n): for k in range(j+1 , n): invcount += 1 return invcount arr = [7 , 16, 2 , 1] print ("Inversion Count after the operation: %d" %(getInvCount(arr))) Output Inversion Count after the operation: 2 Better Approach to count inversions of size 3In this method we will consider the every element of an array as middle element of inversion. It helps to reduce the complexity. For this approach, the time complexity is O(n^2) and auxiliary Space is O(1).
Example 2 def getInvCount(arr, n): invcount = 0 for i in range(1,n-1): small = 0 for j in range(i+1 ,n): small+=1 great = 0; for j in range(i-1,-1,-1): if (arr[i] < arr[j]): great+=1 invcount += great * small return invcount arr = [8, 4, 2, 1] n = len(arr) print("Inversion Count After The Method Run :",getInvCount(arr, n)) Output Inversion Count After The Method Run : 4 Count inversions of size 3 using binary indexed treeIn this method, we count the greater elements and smaller ones too. Then perform the multiply operation greater[] to smaller[] and add it to the final result. Here the time complexity is O(n*log(n)) and auxiliary space denoted as O(n).
Example 3 def getSum( BITree, index): sum = 0 sum += BITree[index] index -= index & (-index) return sum def updateBIT(BITree, n, index, val): while (index <= n): BITree[index] += val index += index & (-index) def getInvCount(arr, n): invcount = 0 maxElement = max(arr) BIT = [0] * (maxElement + 1) for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount if __name__ =="__main__": arr = [8, 4, 2, 1] n = 4 print("Inversion Count After The Operation Done : ", getInvCount(arr, n)) Output Inversion Count After The Operation Done : 6 ConclusionFrom the above discussion, we have learnt how to count inversions of size three in a given array. Hope with this article and the mentioned codes using the particular language, you have got a broad view about this topic.
Update the detailed information about Python Program To Sort The Elements Of The Circular Linked List on the Bellydancehcm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!