You are reading the article Heap Sort Algorithm (With Code In Python And C++) updated in December 2023 on the website Kientrucdochoi.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 Heap Sort Algorithm (With Code In Python And C++)
What is Heap Sort Algorithm?Heap Sort is one of the popular and faster sorting algorithms. It’s built on the complete binary tree data structure. We will search for the maximum element and put it on the top for the max heap. We will put it on the parent node of the binary tree.
Let’s say an array is given, data = [10,5, 7, 9, 4, 11, 45, 17, 60].
In the array, if i-th (i=0,1,2,3 …) index is a parent node then, (2i+1) and (2i+2) will be the left and right children. Creating a complete binary tree with this array will look like this:
We will do the heapify process from the beginning to the end of the array. Initially, if we convert the array to a tree, it will look like the above. We can see that it’s not maintaining any heap property (min-heap or max heap). We will get the sorted array by doing the heapify process for all the nodes.
Application of Heap SortHere’s some usage of the heap sort algorithm:
Construction of “Priority Queues” needs heap sort. Because heapsort keeps the element sorted after each insertion is being made.
Heap Data Structure is efficient in finding the kth largest element in a given array.
Linux Kernel uses the heap sort as a default sorting algorithm as it has O (1) space complexity.
Create Heap Sort with ExampleHere, we will construct a max heap from the following complete binary tree.
The leaf nodes are 17, 60, 4, 11, and 45. They don’t have any child nodes. That is why they are leaf nodes. So, we will start the heapify method from their parent node. Here are the steps:
Step 1) Select the left-most sub-tree. If the child nodes are greater, swap the parent node with the child node.
Here the parent node is 9. And the child nodes are 17 and 60. As, 60 is the largest, 60 and 9 will be swapped to maintain the max heap.
Step 2) Now, the left-most subtree is heapified. The next parent node is 7. This parent has two child nodes, and the largest is 45. So, 45 and 7 will be swapped.
Step 3) Nodes 60 and 4 have the parent node 5. As “5” is smaller than the child node 60, it will be swapped.
Step 4) Now, node 5 has the child node 17,9. This is not maintaining the max heap property. So, 5 will be replaced with 17.
Step 5) Node 10 will be swapped with 60, then swapped with 17. The process will look like the following.
Step 6) Up to step 5, we created the max heap. Every parent node is larger than its child nodes. The root node has the maximum value (60).
Note: To create the sorted array, we need to replace the max valued node with its successor.
This process is called “extract max”. As 60 is the max node, we will fix its position to the 0th index and create the heap without node 60.
Step 7) As 60 is removed, then the next maximum value is 45. We will do the process “Extract Max” again from node 45.
This time we will get 45 and replace the root node with its successor 17.
We need to perform “Extract Max” until all the elements are sorted.
After doing these steps until we extract all the max values, we will get the following array.
What is Binary Heap?A Binary Heap is a kind of complete binary tree data structure. In this kind of tree structure, the parent node is either greater or smaller than the child nodes. If the parent node is smaller, then the heap is called the “Min Heap” and if the parent node is greater, the heap is called the “Max Heap”.
Here’re examples of min heap and max heap.
Min Heap and Max Heap
In the above figure, if you notice the “Min Heap”, the parent node is always smaller than its child nodes. At the head of the tree, we can find the smallest value 10.
Similarly, for the “Max Heap”, the parent node is always larger than the child nodes. The maximum element is present at the head node for the “Max Heap”.
What is “Heapify”?“Heapify” is the principle of the heap that ensures the position of the node. In Heapify, a max heap always maintains a relationship with parent and child, and that is parent node will be larger than the child nodes.
For example, if a new node is added, we need to reshape the heap. However, we might need to change or swap the nodes or rearrange array. This process of reshaping a heap is called the “heapify”.
Here is an example of how heapify works:
Adding a new node and heapify
Here are the steps for heapify:
Step 1) Added node 65 as the right child of node 60.
Step 2) Check if the newly added node is greater than the parent.
Step 3) As it’s greater than the parent node, we swapped the right child with its parent.
How to build the HeapBefore building the heap or heapify a tree, we need to know how we will store it. As the heap is a complete binary tree, it’s better to use an array to hold the data of the heap.
Let’s say an array contains a total of n elements. If “i”th index is a parent node, then the left node will be at index (2i+1), and the right node will be at index (2i+2). We are assuming that the array index begins from 0.
Using this, let’s store a max heap to an array-like following:
Array-based representation of the max heap.
The heapify algorithm maintains the heap property. If the parent does not have the extreme value (smaller or greater), it will be swapped with the most extreme child node.
Here are the steps to heapify a max heap:
Step 1) Start from the leaf node.
Step 2) Find the maximum between the parent and children.
Step 3) Swap the nodes if the child node has a larger value than the parent.
Step 4) Go one level up.
Step 5) Follow steps 2,3,4 until we reach index 0 or sort the entire tree.
Here’s the pseudo-code for recursive heapify (max heap):
def heapify(): input→ array, size, i largest = i left = 2*i + 1 right = 2*i + 2 if left<n and array[largest ] < array[left]: largest = left if right<n and array[largest ] < array[right]: largest = right If largest not equals i: swap(array[i],array[largest]) heapify(array,n,largest) Pseudo Code for Heap SortHere’s the pseudo-code for the heap sort algorithm:
Heapify(numbers as an array, n as integer, i as integer): largest = i left = 2i+1 right= 2i+2 if(left<=n) and (numbers[i]<numbers[left]) largest=left if(right<=n) and (numbers[i]<numbers[right]) largest=right if(largest != i) swap(numbers[i], numbers[largest]) Heapify(numbers,n,largest) HeapSort(numbers as an array): n= numbers.size() for i in range n/2 to 1 Heapify(numbers,n,i) for i in range n to 2 Swap numbers[i] with numbers[1] Heapify(numbers,i,0) Example of Heap Sort Code in C++using namespace std; void display(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << “t”; } cout << endl; } void heapify(int numbers[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && numbers[left] < numbers[largest]) { largest = left; } if (right < n && numbers[right] < numbers[largest]) { largest = right; } if (largest != i) { swap(numbers[i], numbers[largest]); heapify(numbers, n, largest); } } void heapSort(int numbers[], int n) { { heapify(numbers, n, i); } { swap(numbers[0], numbers[i]); heapify(numbers, i, 0); } } int main() { int numbers[] = { 10,5, 7, 9, 4, 11, 45, 17, 60}; int size = sizeof(numbers) / sizeof(numbers[0]); cout<<“Initial Array:t”; display(numbers,size); heapSort(numbers, size); cout<<“Sorted Array (descending order):t”; display(numbers, size); }
Output:
Initial Array: 10 5 7 9 4 11 45 17 60 Sorted Array (descending order): 60 45 17 11 10 9 7 5 4 Example of Heap Sort Code in Python def display(arr): for i in range(len(arr)): print(arr[i], end = "t") print() def heapify(numbers, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and numbers[left] < numbers[largest]: largest = left if right < n and numbers[right] < numbers[largest]: largest = right if largest != i: numbers[i], numbers[largest] = numbers[largest], numbers[i] heapify(numbers, n, largest) def heapSort(items, n): for i in range(n heapify(items, n, i) for i in range(n - 1, -1, -1): items[0], items[i] = items[i], items[0] heapify(items, i, 0) numbers = [10, 5, 7, 9, 4, 11, 45, 17, 60] print("Initial List:t", end = "") display(numbers) print("After HeapSort:t", end = "") heapSort(numbers, len(numbers)) display(numbers)Output:
Initial List: 10 5 7 9 4 11 45 17 60 After HeapSort: 60 45 17 11 10 9 7 5 4 Time and Space Complexity analysis of Heap SortThere’s Time complexity and Space complexity that we can analyze for the heap sort. For time complexity we’ve the following cases:
Best Case
Average Case
Worst Case
The heap is implemented on a complete binary tree. So, at the bottom level of the binary tree, there will be the maximum number of nodes. If the bottom level has n nodes, then the above level will have n/2 nodes.
In this example, Level 3 has four items, level 2 has two items, and level 1 has one item. If there is a total n number of items, the height or total level will be Log2(n). So, inserting a single element could take a maximum of Log(n) iterations.
When we want to take the maximum value from the heap, we just take the root node. Then again, run the heapify. Each heapify takes Log2(n) time. Extracting the maximum takes O(1) time.
Best Case Time Complexity for Heap Sort AlgorithmWhen all the elements are already sorted in the array, it will take O(n) time to build the heap. Because if the list is sorted then inserting an item will take the constant time that is O(1).
So, it will take O(n) time to create a max-heap or min-heap in the best case.
Average Case Time Complexity for Heap Sort AlgorithmInserting an item or extracting a maximum costs O(log(n)) time. So, the average case time complexity for the heap sort algorithm is O(n log(n)).
Worst Case Time Complexity for Heap Sort AlgorithmSimilar to the average case, in the worst-case scenario, we might to perform heapify n times. Each heapify will cost O(log(n)) time. So, the worst-case time complexity will be O(n log(n)).
Space Complexity for Heap Sort AlgorithmHeap sort is an in-place designed algorithm. This means that no extra or temporary memory is needed to perform the task. If we see the implementation, we will notice that we used swap () to perform the exchange of the nodes. No other list or array was needed. So, the space complexity is O(1).
You're reading Heap Sort Algorithm (With Code In Python And C++)
Different Examples Of Union In C With Syntax And Code
Introduction to C Union
Union is a user-defined data type in c, it allows storing of different data elements of different data types to be stored in the same memory location. It provides an efficient way of utilizing the memory, as only one union member can be accessed at any given time. Therefore, the size of a union at any point in time would be equal to the size of its largest element. Though a union is like a structure, the main difference is that in a structure a separated memory is allotted for each member of the structure whereas in the union it’s a shared memory which is equivalent of the size of the largest member.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
A union can be defined as below.
union UnionName { UMember1; UMember2; UMember3; } UnionReference;The C Union members can be accessed using the reference ‘UnionReference’. union is a keyword.
Example of struct and union in memory allocation.
Let us demonstrate the difference between struct and union in memory allocation.
Code:
struct samp_structure { char name1[30]; int e_id; float e_slry; char name2[60]; }s; union s_union { char name1[30]; int e_id; float saly; }u; int main() { printf(“size of structure :%ld bytes n”, sizeof(s)); printf(“size of union : %ld bytesn”, sizeof(u)); return 0; }
Output:
Examples of C UnionLet us see the implementation with the help of the examples mentioned below:
Example #1This is an example to define a C union and accessing its members.
Code:
union test { int tint; float tf; char tstr[20]; }; int main( ) { union test t; t.tint = 100; printf( “record.i : %dn”, t.tint); t.tf= 200.5; printf( “record.f : %fn”, t.tf); strcpy( t.tstr, “Test”); printf( “record.str : %sn”, t.tstr); return 0; }
Output:
Example #2Code:
union test { int tint; float tf; char tstr[20]; }; int main( ) { union test t; t.tint = 100; t.tf = 200.5; strcpy( t.tstr, “Test”); printf( “record.i : %dn”, t.tint); printf( “record.f : %fn”, t.tf); printf( “record.str : %sn”, t.tstr); return 0; }
Output:
If you look at the output carefully, you can see that garbage values have been assigned for int and float because the string was allotted the memory, at last, i.e. since the members share the memory in a union the member whose value is currently stored will have access to the memory.
Example #3Anonymous union is a union that is not named, hence they can be used inside any nested structure or unions. The members of the anonymous union can be directly accessed within the scope of their definition. Similarly, Anonymous structure can be used inside an anonymous union.
Syntax of Anonymous union and structure
union { char anoUChar; int anoUNum; }; struct { char anoSChar; int anoSNum; };Example of anonymous struct union inside a struct.
struct testscope { union { char testChar; int testNum; int testNum2; }; }; int main() { struct testscope ts; ts.testNum = 65; printf(“testchar = %c, testnum = %d,testnum2 = %d”, ts.testChar, ts.testNum,ts.testNum2); return 0; }
Output:
The testchar has been assigned the value ‘A’ because the recent value in the union memory is 65 which was assigned to testNum, hence the corresponding ASCII character is printed.
Note: The members of the union are accessed directly.
Example of anonymous struct inside a union.
Code:
union testscope { struct { char testChar; int testNum; int testNum2; }; }; int main() { union testscope ts; ts.testNum = 65; ts.testChar=’V’; printf(“testchar = %c, testnum = %d,testnum2 = %d”, ts.testChar, ts.testNum,ts.testNum2); return 0; }
Output:
ConclusionThus, the union helps in managing memory efficiently. The drawback of the union is that only the last entered value to the union will only be available. It should be used when members of the union need not be available to be accessed at the same time.
Recommended ArticlesThis is a guide to C Union. Here we discuss the introduction, syntax, and different examples of c union with code implementation. You may also look at the following articles to learn more –
A Simple Guide To Centroid Based Clustering (With Python Code)
This article was published as a part of the Data Science Blogathon.
IntroductionClustering is the process of grouping similar data together. It falls under the category of unsupervised learning, that is the input data does not have labeled responses. Clustering algorithms find their applications in various fields like finance, medicine, and e-commerce. One such example is in e-commerce a possible use case would be to group similar customer segments based on their purchasing styles to give them offers or discounts.
In clustering every data point belongs to some cluster however a single data point cannot be present in more than one cluster. The performance of a clustering algorithm can be measured by metrics such as the Dunn index (DI). A large inter-cluster distance(well separated) and a smaller inter-cluster distance(compact) clusters have a higher value of DI.
Different approaches can be employed in clustering based on your dataset, such as
Centroid based clustering
Hierarchical clustering/Connectivity based clustering
Density-based clustering
We would focus on centroid-based clustering in this article.
Centroid based clusteringK means algorithm is one of the centroid based clustering algorithms. Here k is the number of clusters and is a hyperparameter to the algorithm. The core idea behind the algorithm is to find k centroids followed by finding k sets of points which are grouped based on the proximity to the centroid such that the squared distances of the points in the cluster to the centroid are minimized. This optimization is a very hard problem hence an approximation is used to solve the problem. One such approximation is Lloyd’s algorithm whose implementation is as below.
Implementation:-
Select k points at random as centroids/cluster centers.
Assign data points to the closest cluster based on Euclidean distance
Calculate centroid of all points within the cluster
Repeat iteratively till convergence. (Same points are assigned to the clusters in consecutive iterations)
The only problem with this implementation however is that it suffers from initialization sensitivity. On selecting different centroids in the initialization stage different clusters are generated. Workaround to the problem would be
to repeat k means multiple times with different initializations and select the best result.
instead of using random initialization to use a smart initialization process such as K means ++.
In some cases it is difficult to interpret centroids, for example, if you are dealing with text data, centroids are not interpretable. An approach to deal with this would be to use the K medoids algorithm. It would select the most centered member within the data as a cluster center and is generally more robust to outliers than other means.
You may wonder how is the best value for k is selected?Elbow or knee method is used to determine the best k. We try the k means implementation for multiple k values and plot them against our sum of squared distances from the centroid(loss function). The elbow of the curve (where the curve visibly bends) is selected as the optimum k.
Advantages of using K means:-
The algorithm in most cases runs in linear time.
Simple and intuitive to understand
Limitations of using K means:-
A number of clusters need to be known beforehand.
It is not very robust to outliers.
Does not work very well with nonconvex shapes.
Tries to generate equal-sized clusters
Let’s run through a code example of K means in action.
As input, I have generated a dataset in python using sklearn.datasets.make_blobs.
We have a hundred sample points and two features in our input data with three centers for the clusters.
We then fit our data to the K means clustering model as implemented by sklearn.
We have used our initialization method to be k means++ instead of random and set our k to be 3
Try out the above code in the live coding window below:
We can see the three centers of clusters printed and kmeans.labels_ gives us the cluster each of our hundred points is assigned to.
To better visualize this we use the below code to represent the clusters graphically.
We can see that our k means algorithm did a very good job in clustering our dataset.
Thank you for reading along, I am Alicia Ghantiwala a data science enthusiast and a software engineer at BNP Paribas.
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.
Related
How To Sort Alphabetically In Excel With Multiple Columns
Ever find yourself staring at a heap of info in Excel, scratching your head about how to make it all neat and tidy? You’re in the right place! Today, we’re tackling one of Excel’s superpowers: sorting data alphabetically across multiple columns.
In this article, we’ll get our hands dirty with Excel and teach you how to sort data alphabetically across multiple columns. We’ll break down the basics of how Excel’s sorting function works, and guide you through the process step-by-step, using clear, easy-to-follow instructions.
So, let’s dive in and transform you into an Excel whiz!
Alright, before we dive into the nitty-gritty of multi-column sorting, let’s first take a moment to understand what Excel’s sorting function is all about.
Think of the sorting function as your own personal data organizer. It’s a feature that allows you to arrange your data in a particular order — and that’s super handy when dealing with tons of information. Excel’s sorting function is like having a personal librarian who knows exactly where each book should go.
When it comes to sorting, Excel gives you two options: ascending or descending order.
Ascending order means arranging the data from smallest to largest, or in the case of text, from A to Z.
Descending order means arranging the data from largest to smallest, or from Z to A for text.
But here’s where things get a bit more interesting. Excel doesn’t limit you to sorting just one column. It lets you sort multiple columns, which means you can arrange your data based on more than one criterion.
Imagine you’re dealing with a list of names, with separate columns for first name and last name. Excel allows you to sort the list by last name and then sort those with the same last names by first name. Pretty cool, right?
So, in a nutshell, Excel’s sorting function is a powerful tool that helps you make sense of your data. It organizes your information in a logical, easy-to-read manner, saving you time and effort.
Now that we’ve got the basics down, let’s move on to the fun part — learning how to sort data alphabetically in columns!
Before we jump into the deep end with multi-column sorting, let’s take a quick dip in the shallow end by sorting a single column in ascending order and then descending order.
To sort a single column in ascending order, follow the below steps:
Step 1: Open your Excel worksheet
Kick things off by opening the worksheet that has the raw data you want to sort.
Step 2: Select the data to be sorted
Step 3: Go to the Data tab and find the Sort and Filter group
If you want to sort a single column in descending order, you have to follow the same process. Here are the steps:
Step 1: Open your Excel worksheet
Kick things off by opening the worksheet that has the data you want to sort.
Step 2: Select the data to be sorted
Step 3: Go to the Data tab and find the Sort and Filter group.
And there you have it! You’ve just sorted a single column in ascending and descending order in Excel. Now, let’s take things up a notch and sort multiple columns.
Alright, now that you’ve mastered single-column sorting, it’s time to turn up the heat and tackle multiple columns. Don’t sweat it, though — if you’ve got the single column down, this is just a hop, skip, and jump away.
Step 1: Open your Excel worksheet
Start by opening the worksheet that holds all the data you want to sort.
Step 2: Select your data
Step 4: In the Sort dialog box, choose the first column you want to sort under the Sort by drop-down menu and specify the sorting order
Excel allows you to sort data in more ways than just alphabetically. You can also sort by color, by cell icon, or even by a custom list you’ve created.
For instance, if you have a column that uses cell color to indicate priority levels, you can sort your data based on those colors.
Simply go to the “Sort” dialog box, select the column, and then choose “Sort by Color” from the “Sort On” drop-down.
We’ve covered how to sort by more than one column, but you can also sort by more than one criterion within a single column.
For example, you might want to sort a column of text by cell color first and then alphabetically.
This can be done by adding two sort levels for the same column, each with a different “Sort On” criterion.
The SORT function in Excel can help you sort data based on multiple columns. Here is an example:
=SORT(range, [sort_index1], [sort_order1], [sort_index2], [sort_order2], ...)In this formula, you have to specify the following:
The data range
Columns to sort by (index)
Sort order (1 for ascending, -1 for descending)
You can add more columns to sort by adding more sort_index and sort_order pairs to the SORT function.
Data with merged cells can be tricky to sort. When you try to sort a range that includes merged cells, Excel will give you an error message.
But don’t panic, there’s a workaround.
You’ll need to unmerge all the cells, sort the data, and then reapply the merging. Just make sure to copy the merged cell’s value to all of the unmerged cells before sorting.
Next, we’ll troubleshoot some common issues you might run into when sorting Excel columns.
Even though Excel is a powerful tool, it’s not without its quirks. You might run into a few bumps along the road while sorting but don’t fret. We’re here to help you troubleshoot some of the most common issues.
Sometimes your data won’t sort correctly because it isn’t stored in the correct format. For instance, if numbers are stored as text, they might not sort numerically.
To apply a common cell format to your data, press Ctrl+1, go to the Number tab, and select the suitable format under “Category.”
If your data isn’t sorting as expected, check for extra spaces at the start or end of your cells. Excel includes these spaces in its sorting, which might throw off your results.
You can remove extra spaces using Excel’s TRIM function by typing “=TRIM(A1)” in a new cell (if A1 is the cell containing the leading space) and then copy the result to the original cell.
Also, make sure that there are no unexpected blank rows or cells in your dataset. Blank cells can affect your sorting process. If you find any blank cells, you can either delete the entire row or fill it with the correct data.
Before sorting your data, it’s a good idea to remove duplicate rows. This ensures that your sorted data is accurate and representative. Follow these steps to remove duplicates:
Excel will remove any duplicate rows and shows a message that how many duplicate rows were removed.
If Excel crashes or hangs during sorting, your worksheet might be too large, or your computer might not have enough resources. Try closing other applications to free up memory.
If your worksheet is large, consider breaking it down into smaller, more manageable chunks.
Remember, sorting can be a complex process, especially with large datasets. If you run into trouble, take a step back and try to troubleshoot one issue at a time. You’ve got this!
Now that you’ve gotten a handle on sorting in Excel, how about we sprinkle in a little extra magic?
To help you become an even more efficient data maestro, we’re going to share some additional tips and tricks that can make your sorting tasks quicker, smoother, and generally more awesome.
Keyboard shortcuts can save you time and enhance your productivity when working with Excel data. Here are a few shortcuts for sorting alphabetically:
Alt + A + S + A: Sort the selected data alphabetically from A to Z.
Alt + A + S + D: Sort the selected data alphabetically from Z to A.
Alt + D + S: Open the Sort dialog box to apply custom sorting.
Remember to select the desired data range or cell in the same row or column before using these keyboard shortcuts. Otherwise, you will get the wrong results.
Excel allows you to save your custom sort settings to reuse them later. Follow these steps to save your sorting options:
Step 1: Select your data range or the cells within the column you want to sort
Step 3: In the “Sort” dialog box, select the column name from the Sort by drop-down. Note that if there are no column headers, Excel is showing column letters.
Now your custom sort settings are saved, and you can see them in the Custom Lists section of the Order drop-down menu in the Sort dialog box for future use.
But remember, this is just the beginning. Excel is an incredibly powerful tool, with countless more features and functionalities waiting to be discovered.
This guide should have armed you with the skills and knowledge to tackle data sorting in Excel like a pro. But don’t stop here. The real magic happens when you take these lessons and apply them to your own work.
To learn more Excel tricks, check out the video below:
Python Program To Sort A Tuple By Its Float Element
This article will demonstrate how write a Python program to sort a tuple (made up of float elements) using its float elements. Here, we’ll look at both how to sort using the in-built sorted() function and how to sort using the in-place method of sorting.
Input-Output ScenariosFollowing is an input and its output scenario determining the sorting of a tuple by its float element −
Scenario-1 Input: tuple = [(‘Dengu’, ’54.865’), (‘Malaria’, ‘345.743’), (‘Corona’, ‘456.864’), (‘Typhoid’, ‘35.285’), (‘Jaundice’, ’83.367’)] Output: [(‘Corona’, ‘456.864’), (‘Malaria’, ‘345.743’), (‘Jaundice’, ’83.367’), (‘Dengu’, ’54.865’), (‘Typhoid’, ‘35.285’)]In the above scenario we can see that the tuples have been sorted in the descending order using its float elements.
Scenario-2 Input: tuple = [(‘638’, ’54.865’), (‘932’, ‘345.743’), (‘256’, ‘456.864’), (‘843’, ‘35.285’), (‘246’, ’83.367’)] Output: [(‘256’, ‘456.864’), (‘932’, ‘345.743’), (‘246’, ’83.367’), (‘638’, ’54.865’), (‘843’, ‘35.285’)]In the above scenario we can see that the tuple has been sorted in descending order by its float elements and not by its integer values.
Using sorted() methodWithout changing the initial sequence, Sorted() sorts a tuple and always returns a tuple with the items in a sorted order. Here, we tried to use all three of the arguments i.e. iterable, key (optional) and reverse (optional), two of which are optional.
AlgorithmThe following algorithm describes the ways to sort a tuple by its float element using sorted() method −
provided a list
using sorted to sort ().
Any iterator that needs to be sorted, whether it be a collection (dictionary, set, frozenset), sequence (list, tuple, string), or another type.
Using the function key(optional) as a basis for sort comparison would act as a key.
The iterable would be sorted in reverse (descending) order if Reverse (optional) were set to true. By default, it is set to false.
ExampleFollowing is the code of Python for sorting a tuple by its float element using sorted() method −
return
(
sorted
(
X
,
key
=
lambda
n
:
float
(
n
[
1
]
)
,
reverse
=
True
)
)
X
=
[
(
‘Dengu’
,
‘54.865’
)
,
(
‘Malari’
,
‘345.743’
)
,
(
‘Corona’
,
‘456.864’
)
,
(
‘Typhoi’
,
‘35.285’
)
,
(
‘Jaundice’
,
‘83.367’
)
]
(
“Sorting of Tuples Using Its Float Element ::”
,
sort_tuple
(
X
)
)
OutputFollowing is an output of the above code −
Sorting of Tuples Using Its Float Element :: [('Corona', '456.864'), ('Malari', '345.743'), ('Jaundice', '83.367'), ('Dengu', '54.865'), ('Typhoi', '35.285')] Using sort() methodThe tuple’s actual content is changed during this method of sorting, whereas the original tuple’s content was left unchanged during the previous approach.
AlgorithmThe following algorithm describes the ways to sort a tuple by its float element using sort() method −
Create a new Tuple List.
Define the Sort function (For Sorting Tuple).
Set the second element as the sorting key.
Use lambda sublist.
Print the outcome.
ExampleIn this code, using this method of sorting changes the tuple’s actual contents. The sort() function sorts the elements of a list in ascending or descending order by using the default comparisons operator between items. Use the key argument to specify the function name to be used for comparison rather than the default operator −
tuple
.
sort
(
key
=
lambda
x
:
float
(
x
[
1
]
)
,
reverse
=
True
)
(
tuple
)
tuple
=
[
(
‘638’
,
‘54.865’
)
,
(
‘932’
,
‘345.743’
)
,
(
‘256’
,
‘456.864’
)
,
(
‘843’
,
‘35.285’
)
,
(
‘246’
,
‘83.367’
)
]
sort
(
tuple
)
OutputFollowing is an output of the above code −
[('256', '456.864'), ('932', '345.743'), ('246', '83.367'), ('638', '54.865'), ('843', '35.285')] Using Binary Search operationIn our code, we have a list of tuples that we must sort using the tuple’s second member, the sorting index. We’ll effectively use a sorting method, except we’ll use the second element of the tuple rather than the first value from the list.
AlgorithmThe following algorithm describes the ways to sort a tuple by the index of sorting by its float element using binary search operation −
List initialization.
Print the initial List.
Define the tuple list’s length.
Using the binary function to sort.
Print the outcome
ExampleThe binary sorting method is used in this program to perform the sorting. The list will be sorted using an index determined by the second item of the tuple −
tuple_list
=
[
(
‘638’
,
54.865
)
,
(
‘932’
,
345.743
)
,
(
‘256’
,
456.864
)
,
(
‘843’
,
35.285
)
,
(
‘246’
,
83.367
)
]
(
“The orignal list is : “
,
str
(
tuple_list
)
)
Len
=
len
(
tuple_list
)
for
i
in
range
(
0
,
Len
)
:
for
j
in
range
(
0
,
(
Len
–
i
–
1
)
)
:
if
(
tuple_list
[
j
]
[
1
]
<
tuple_list
[
j
+
1
]
[
1
]
)
:
temp
=
tuple_list
[
j
]
tuple_list
[
j
]
=
tuple_list
[
j
+
1
]
tuple_list
[
j
+
1
]
=
temp
(
“The sorted list is : “
,
str
(
tuple_list
)
)
OutputFollowing is an output of the above code −
The orignal list is : [('638', 54.865), ('932', 345.743), ('256', 456.864), ('843', 35.285), ('246', 83.367)] The sorted list is : [('256', 456.864), ('932', 345.743), ('246', 83.367), ('638', 54.865), ('843', 35.285)]Advantages And Working Of C++ Endl With Examples
Introduction to C++ endl
Web development, programming languages, Software testing & others
Syntax:
The syntax of C++ endl is as follows:
cout<< statement to be executed <<endl; Working of C++ endl
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal.
But if are using flush in our program, the entire output data will be flushed to the terminal directly without storing anything in the buffer.
Whenever there is a need to insert the new line character to display the output in the next line while flushing the stream, we can make use of endl in C++.
Whenever there is a need to insert the new line character to display the output in the next line, we can make use of endl in ‘n’ character but it does not do the job of flushing the stream. So if we want to insert a new line character along with flushing the stream, we make use of endl in C++.
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal.
Examples of C++ endlFollowing are the examples of c++ endl:
Example #1C++ program to demonstrate endl in a program to print the given statements in a new line:
Code:
using namespace std; intmain( ) { cout<< "Welcome to "; cout<< "C#"<<endl; cout<< "Learning is fun"<<endl; }In the above program, the header file iostream is imported to enable us to use cout in the program. Then a namespace called std is defined. Then the main method is called. Then the cout is used to output the statement. Then again cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream.
Example #2C++ program to demonstrate endl in a program to prompt the user to enter his or her name while using endl to print each statement in the next new line while flushing the output stream:
using namespace std; intmain( ) { string name; cout<< "Please enter your name: " <<endl; cout<< "My name is: "<< name <<endl; }Output:
In the above program, the header file iostream is imported to enable us to use cout in the program. Then a namespace called std is defined. Then the main method is called. Then a string variable is used to store the name entered by the user. Then cout is used to output the statement to prompt the user to enter his name withendl used in the statement so that the next statement is printed in the next new line. Then in takes, the name of the user entered by the user. Then cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream.
Advantages
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal.
But if are using flush in our program, the entire output data will be flushed to the terminal directly without storing anything in the buffer.
By making use of endl, we can insert the new line character to display the output in the next line while flushing the stream.
There is no necessity to explicitly use flush if we are using endl in the program to flush the output stream.
Recommended ArticlesThis is a guide to C++ endl. Here we also discuss the introduction and working of c++ endl along with different examples and its code implementation. You may also have a look at the following articles to learn more –
Update the detailed information about Heap Sort Algorithm (With Code In Python And C++) on the Kientrucdochoi.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!