0% found this document useful (0 votes)
30 views6 pages

Python Sorting Algorithms for Students

The document discusses algorithms for sorting lists of characters and student data. It provides Python code to implement bubble sort, selection sort, and insertion sort. The code defines a Student class to hold student registration numbers, names, courses, and GPAs. It generates sample student data and uses the sorting algorithms to arrange the data by registration number and descending GPAs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views6 pages

Python Sorting Algorithms for Students

The document discusses algorithms for sorting lists of characters and student data. It provides Python code to implement bubble sort, selection sort, and insertion sort. The code defines a Student class to hold student registration numbers, names, courses, and GPAs. It generates sample student data and uses the sorting algorithms to arrange the data by registration number and descending GPAs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BSCS-402 DATA STRUCTURE

LAB 9
[Link] the list of characters: [‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’]. Show how this list is
sorted

using the following algorithm.

• Bubble Sort
• Selection Sort
• Insertion Sort

Q2. Create a structure/class for a group of 50 students holding data for their Regn
no., Name, Course, CGPA.
a) Call linear search function to display data of student with a particular Regn no.
b) Call bubble sort function to arrange data of students according to Regn no.
c) Apply binary search on the above output (part b) to display data of a student
with a particular Regn no.
d) Use and modify Insertion sort logic to arrange data of students in descending
order of CGPA.

Q2.
[Link] LAB_9_Q2.PY
1 from SpecialSearchingLibrary import LineraSearch as ls
2 from SpecialSearchingLibrary import bubbleSort as bs
3 from SpecialSearchingLibrary import bSearch as Bs
4 from SpecialSearchingLibrary import selectionSort as ss
5
6 class Uni:
7 def __int__(self,reg,name,course,cgpa):
8 [Link] = reg
9 [Link] = name
10 [Link] = course
11 [Link] = cgpa
12
13 def reg(self,reg):
14 [Link] = reg
15 def name(self,name):
16 [Link] = name
17 def course(self,course):
18 [Link] = course
19 def cgpa(self,cgpa):
20 [Link] = cgpa
21
22 def Students(self):
23 print("REG NO:",[Link],"\tName :",[Link],"\tCourse
24 :",[Link],"\tCGPA:",[Link])
25
26
27 s = []
28 # n = int(input("Enter total Number of Students:"))
29 # for i in range(n):
30 new_student = Uni()
31
32 new_student.name("Anas")
33 new_student.reg(12)
34 new_student.course("BSCS")
35 new_student.cgpa(3.1)
36 [Link](new_student)
37
38 new_student = Uni()
39 new_student.name("Izhan")
40 new_student.reg(23)
41 new_student.course("BSCS")
42 new_student.cgpa(3.5)
43 [Link](new_student)
44
45 new_student = Uni()
46 new_student.name("Umer")
47 new_student.reg(34)
48 new_student.course("BSCS")
49 new_student.cgpa(3.2)
50 [Link](new_student)
51
52 new_student = Uni()
53 new_student.name("AHmed")
54 new_student.reg(14)
55 new_student.course("BSCS")
56 new_student.cgpa(3.4)
57 [Link](new_student)
58
59
60
61 print("[Link] linear search function to display data of student with a
62 particular Regn no.")
63 print("[Link] bubble sort function to arrange data of students
64 according to Regn no.")
65 print("[Link] binary search on the above output (part b) to display
66 data of a student with a particular Regn no.")
67 print("[Link] and modify Insertion sort logic to arrange data of
68 students in descending order of CGPA.")
69 print("[Link]")
70 while True:
71 a= int(input("Selct an Option: "))
72 if a == 1:
73 pik = int(input("Enter Regn No :"))
74 print(ls(s, pik))
75 elif a==2:
76 for i in bs(s):
77 [Link]()
78 elif a == 3:
79 pik = int(input("Enter Regn No :"))
80 print(Bs(bs(s),pik, 0, len(s)-1))
81 elif a == 4:
82 for i in ss(s):
83 [Link]()
84 elif a == 5:
85 break
86 else:
87 print("Choose from Options!!!")

Result:
Q2.
[Link] LAB_9_Q2.PY
1 def bubbleSort( theSeq ):
2 swap = 0
3 comparisons = 0
4 n = len( theSeq )
5 # Perform n-1 bubble operations on the sequence
6 for i in range( n - 1 ) :
7 # Bubble the largest item to the end.
8 for j in range( n-1 ) :
9 comparisons +=1
10 if theSeq[j] > theSeq[j + 1]: # swap the j and j+1 items.
11 tmp = theSeq[j]
12 theSeq[j] = theSeq[j + 1]
13 theSeq[j + 1] = tmp
14 swap += 1
15 print("Swapping times:",swap)
16 print("Comparison times:", comparisons)
17 return theSeq
18
19 print("Bubble sort")
20 print(bubbleSort(["P", "Y", "T", "H", "O", "N"]))
21
22
23 print()
24 print("Selection sort")
25 def selectionSort( theSeq ):
26 swap = 0
27 comparisons = 0
28 n = len( theSeq )
29 for i in range( n - 1 ):
30 # Assume the ith element is the smallest.
31 smallNdx = i
32 # Determine if any other element contains a smaller value.
33 for j in range( i + 1, n ):
34 comparisons += 1
35 if theSeq[j] < theSeq[smallNdx] :
36
37 smallNdx = j
38
39 # Swap the ith value and smallNdx value only if the smallest value
40 is
41 # not already in its proper position. Some implementations omit
42 testing
43 # the condition and always swap the two values.
44 if smallNdx != i :
45 tmp = theSeq[i]
46 theSeq[i] = theSeq[smallNdx]
47 theSeq[smallNdx] = tmp
48 swap += 1
49
50 print("Swapping times:", swap)
51 print("Comparison times:", comparisons)
52 return theSeq
53
54 print(selectionSort(["P", "Y", "T", "H", "O", "N"]))
55
56 # Sorts a sequence in ascending order using the insertion sort
57 algorithm.
58
59 print()
60 print("Insertion sort")
61 def insertionSort( theSeq ):
62 swap = 0
63 comparisons = 0
64 n = len( theSeq )
65 # Starts with the first item as the only sorted entry.
66 for i in range( 1, n ) :
67 # Save the value to be positioned.
68 value = theSeq[i]
69 # Find the position where value fits in the ordered part of the list.
70 pos = i
71 comparisons +=1
72 while pos > 0 and value < theSeq[pos - 1] :
73 swap +=1
74 # Shift the items to the right during the search.
75 theSeq[pos] = theSeq[pos - 1]
76 pos -= 1
77
78 # Put the saved value into the open slot.
79 theSeq[pos] = value
80
81 print("Swapping times:", swap)
82 print("Comparison times:", comparisons)
83 return theSeq
84
85 print(insertionSort(["P", "Y", "T", "H", "O", "N"]))
Result:

Common questions

Powered by AI

Bubble sort first compares pairs of adjacent elements, swapping them if they are in the wrong order. For the list ['P', 'Y', 'T', 'H', 'O', 'N'], the process is as follows: 1. Compare 'P' and 'Y'. No swap needed. 2. Compare 'Y' and 'T'. Swap them to get ['P', 'T', 'Y', 'H', 'O', 'N']. 3. Compare 'Y' and 'H'. Swap them to get ['P', 'T', 'H', 'Y', 'O', 'N']. 4. Compare 'Y' and 'O'. Swap them to get ['P', 'T', 'H', 'O', 'Y', 'N']. 5. Compare 'Y' and 'N'. Swap them to get ['P', 'T', 'H', 'O', 'N', 'Y']. This completes the first pass. The algorithm makes multiple passes until no swaps are needed, which sorts the list into ['H', 'N', 'O', 'P', 'T', 'Y'] after all necessary passes .

The data structure for handling student data is designed to support easy sorting and searching through encapsulation within a class. Each student is represented as an instance of the 'Uni' class, with attributes such as registration number, name, course, and CGPA. This structure allows implementation of methods to interact with student data, such as sorting by registration number using bubble sort and searching using binary search. By organizing data in this way, it becomes straightforward to apply sorting and searching algorithms, enhancing data manipulation capabilities .

Both the bubble sort and selection sort algorithms involve different numbers of comparisons and swaps. For bubble sort, it performs comparisons for every adjacent pair of elements and swaps them if necessary, leading to multiple swaps if elements are out of order; this involves several swaps and a higher number of comparisons as each adjacent pair is compared over multiple passes . In contrast, selection sort makes comparisons to find the minimal element in each pass, performing a swap only once per pass, which results in fewer swaps but may involve a similar number of comparisons depending on the distribution of elements .

Selection sort offers the advantage of reduced swap operations over bubble sort, particularly useful for partially sorted data. While both algorithms have similar time complexities for worst-case scenarios, selection sort only performs a single swap per pass when placing the smallest remaining element in its correct position, which can be more efficient than bubble sort's repeated swaps needed every time adjacent pairs are out of order. Consequently, selection sort may require fewer swaps and can end up being faster for datasets that do not require extensive rearranging .

The linear search checks each student record sequentially against the target registration number until a match is found or the list is exhausted. The function iterates through each element in the student list, compares the registration number of each student with the target number, and if a match is found, it returns the corresponding student data. If no match is found by the end of the list, it typically outputs that the student is not found. This straightforward approach ensures that all elements are checked for potential matches .

Binary search significantly optimizes the search process by reducing the number of comparisons needed to find a specific item. After sorting the student records by registration number using a method like bubble sort, binary search locates a specific record by repeatedly dividing the sorted list in half and narrowing down the potential locations, rather than checking each item sequentially as a linear search does. This logarithmic complexity results in much faster search times, particularly advantageous for large datasets .

Bubble sort has a time complexity of O(n^2), which makes it inefficient for large datasets such as 50 student records. The primary challenges include its high number of comparisons and swaps, leading to slow performance. Each bubble sort pass requires multiple element comparisons, resulting in poor scalability as dataset size increases. Additionally, for lists that are significantly out of order, bubble sort's inefficiency is more pronounced, leading to much longer execution times compared to more efficient sorting algorithms like quicksort or mergesort .

Using Python classes streamlines the implementation and management of student data through encapsulation and abstraction. The class structure allows methods such as sorting and searching to be associated directly with student data, enhancing readability and organization. Libraries further extend functionality by providing pre-built, optimized algorithms that reduce the need to manually code common operations such as sorting. This enhances efficiency as developers can use and modify these algorithms, applying them to the structured data seamlessly .

Although insertion sort can be efficient for nearly sorted data, it has inherent weaknesses such as low sorting speed for larger, unsorted datasets. Its O(n^2) time complexity means it becomes significantly slower as the number of elements increases. Each insertion sort step involves shifting elements to insert a new one in the correct position, which can lead to poor performance when many shifts are required. It doesn’t handle large, unsorted data well compared to more advanced algorithms like quicksort .

To modify the insertion sort algorithm to arrange students by descending CGPA, you need to change the comparison operator from '<' to '>' in the while condition. This reverses the order of sorting so that higher CGPA values are positioned earlier in the sequence. Specifically, the comparison `while pos > 0 and value < theSeq[pos - 1]` should be modified to `while pos > 0 and value > theSeq[pos - 1]` within the insertion sort loop in the class .

You might also like