exam TStu TExam
1 91 25
2 168 20
3 2080 46
4 680 56
5 15 12
6 680 22
7 166 20
How to sort in descending order like this..
4 680 56
3 2080 46
1 91 25
....................................
exam TStu TExam
1 91 25
2 168 20
3 2080 46
4 680 56
5 15 12
6 680 22
7 166 20
How to sort in descending order like this..
4 680 56
3 2080 46
1 91 25
....................................
The table in the first post from needs to be sorted by a specific column (descending). Replies from and correctly point out there are many techniques; here is a compact, practical C++ pattern that is easy to drop into a program and works for most cases.
Represent each row as a small struct, read the triples into a std::vector, then call std::sort with a comparator that compares the target column descending (and any secondary keys you want). This uses standard library routines (O(n log n)) and keeps the code clear and maintainable:
#include <iostream>
#include <vector>
#include <algorithm>
struct Row { int exam, tStu, tExam; };
int main() {
std::vector<Row> rows;
Row r;
// skip header if present, then read triples until EOF
while (std::cin >> r.exam >> r.tStu >> r.tExam) rows.push_back(r);
std::sort(rows.begin(), rows.end(),
[](const Row& a, const Row& b) {
if (a.tExam != b.tExam) return a.tExam > b.tExam; // primary: descending TExam
if (a.tStu != b.tStu) return a.tStu > b.tStu; // secondary
return a.exam < b.exam; // tertiary
});
for (const auto& x : rows)
std::cout << x.exam << '\t' << x.tStu << '\t' << x.tExam << '\n';
} Notes and troubleshooting:
std::stable_sort instead of std::sort.std::string line; std::getline(std::cin, line); before parsing numbers.Row and compare the key in the comparator.This approach is simple, robust, and easy to extend for additional keys or different input formats.
Jump to Post— Laiq Ahmed 42Hey Sorting is a huge topic and there are several ways of sorting the data.
which technique you want to use to sort this data.
Radix sort can do a job.
lets understand what you want1 91 25
2 168 20
3 2080 46
4 680 56
5 …
Hey Sorting is a huge topic and there are several ways of sorting the data.
which technique you want to use to sort this data.
Radix sort can do a job.
lets understand what you want
1 91 25
2 168 20
3 2080 46
4 680 56
5 15 12
6 680 22
7 166 20
you want to start sorting the data from the last two digits.
Algorithm goes like this.
read the list of numbers in arrays.
use suitable sorting algorithm.
the tricky part is how you would get the last two numbers to do comparision (if you are using comparision sorting technique). ? (its simple dear, try gettting the
(number % 100). it will give you last two digits. :).
Perform sorting.
Hope this help.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.