Sorting the Data from a File
Create a text file that contains the names and marks of students in a class.Then, read the data from the file, apply the Quick Sort algorithm to sort the students based on their marks in decreasing order, and store the sorted data back into a file
This is a very practical file handling + sorting algorithm problem 👏.
🎯 Goal
You need to:
-
Create a text file that contains student names and marks.
-
Read data from that file.
-
Sort students by marks in decreasing order using Quick Sort.
-
Write the sorted data back to a new file.
🧠 Algorithm
Input Format (in text file)
Steps
-
Read the data from file
-
Open the input file (e.g.,
students.txt
) in read mode. -
Read each line → extract
name
andmarks
. -
Store them in an array of structures.
-
-
Apply Quick Sort
-
Choose a pivot (first or last element).
-
Partition the array so that:
-
Marks greater than pivot are on the left (for decreasing order).
-
Marks smaller than pivot are on the right.
-
-
Recursively apply Quick Sort on both halves.
-
-
Write back to file
-
Open a new output file (e.g.,
sorted_students.txt
). -
Write the sorted list to the file.
-
⏱ Time Complexity
-
Best/Average: O(n log n)
-
Worst: O(n²) (rare, depends on pivot selection)
Comments
Post a Comment