Docsity

Introduction to Sorting in python, Study notes of Computer science

Toggle sidebar
bg1
STUDENT NOTES || CHAPTER 5
SORTING
1
2 MARKS QUESTIONS
1. What is sorting? Give one real-life
example. Answer:
Sorting is the process of arranging or ordering a given collection of elements in a particular order, such
as ascending or descending.
Example: Words in a dictionary are sorted in alphabetical order to make searching easier.
2. Define pass and swap in the context of Bubble
Sort. Answer:
A pass refers to one complete iteration through the list during sorting.
A swap is the process of exchanging the positions of two adjacent elements if they are not in the desired
order.
3. Write the syntax of swapping two elements in Python with an example.
Answer:
Syntax:
a,
b =
b,
a
Example:
list[j], list[j+1]
=
list[j+1], list[j]
This swaps the elements at index j and j+1 in a list.
4. Differentiate between Bubble Sort and Selection Sort (any two
points). Answer:
Bubble Sort Selection Sort
Repeatedly compares and swaps adjacent
elements.
Pushes the largest element to the end in
Selects the smallest element and swaps it with the
leftmost unsorted element.
Places the smallest element at the beginning in each
pass.
5. What is the purpose of using a flag in Selection Sort algorithm?
Answer:
The
flag
is used to check whether a smaller element than the current minimum was found in the
current pass. If
flag
= 1, a swap is needed; otherwise, no swap is performed.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Introduction to Sorting in python and more Study notes Computer science in PDF only on Docsity!

SORTING

2 MARKS QUESTIONS

1. What is sorting? Give one real-life example. Answer: Sorting is the process of arranging or ordering a given collection of elements in a particular order, such as ascending or descending. Example: Words in a dictionary are sorted in alphabetical order to make searching easier. 2. Define pass and swap in the context of Bubble Sort. Answer: A pass refers to one complete iteration through the list during sorting. A swap is the process of exchanging the positions of two adjacent elements if they are not in the desired order. 3. Write the syntax of swapping two elements in Python with an example. Answer: Syntax: a, b = b, a Example: list[j], list[j+ 1 ] = list[j+ 1 ], list[j] This swaps the elements at index j and j+1 in a list. 4. Differentiate between Bubble Sort and Selection Sort (any two points). Answer: Bubble Sort Selection Sort Repeatedly compares and swaps adjacent elements. Pushes the largest element to the end in Selects the smallest element and swaps it with the leftmost unsorted element. Places the smallest element at the beginning in each pass. 5. What is the purpose of using a flag in Selection Sort algorithm? Answer: The flag is used to check whether a smaller element than the current minimum was found in the current pass. If flag = 1 , a swap is needed; otherwise, no swap is performed.

SORTING

6. Give one example where Insertion Sort is more efficient than other sorts. Explain why. Answer: Insertion Sort is more efficient for nearly sorted lists because it requires fewer comparisons and shifts, giving it a best-case time complexity of O(n). 7. Write the initial list and final sorted list after applying Insertion Sort on: [8, 7, 13, 1, - 9, 4]. Answer: Initial List: [8, 7, 13, 1, -9, 4] Final Sorted List: [-9, 1, 4, 7, 8, 13] 8. Distinguish between shifting and swapping in the context of sorting. Answer: Shifting means moving elements one position to the right to make space (used in Insertion Sort). Swapping means exchanging two elements’ positions directly (used in Bubble and Selection Sort). 9. Explain time complexity with an example from the chapter. Answer: Time complexity is the amount of time an algorithm takes to run, depending on input size. Example: Bubble Sort has O(n²) time complexity because it uses a nested loop to perform n × (n – 1)/ comparisons. 10. Write the output of the following Bubble Sort implementation on the list [8, 7, 13, 1, - 9, 4]. Also, mention how many passes are needed. Answer: Output: [-9, 1, 4, 7, 8, 13] Passes Needed: 5 (as the list contains 6 elements)

3 MARKS QUESTIONS

1. Explain the concept of Bubble Sort with an example. Answer: Bubble Sort compares adjacent elements and swaps them if they are in the wrong order. After each pass, the largest element is moved to its correct position at the end. This process is repeated for n− passes for a list of n elements.

SORTING

Insertion Sort builds a sorted list one element at a time. Each new element is compared with elements in the sorted list and inserted into its correct position by shifting larger elements to the right.

SORTING

Example: [8, 7, 13, 1, -9, 4] becomes [-9, 1, 4, 7, 8, 13] after applying Insertion Sort.

6. Write the algorithm for Bubble Sort and explain its steps. Answer: Algorithm:

  1. Set i = 0
  2. While i < n, repeat steps 3–
  3. Set j = 0
  4. While j < n - i - 1, repeat steps 5–
  5. If list[j] > list[j+1]
  6. Swap list[j] and list[j+1]
  7. Increment j
  8. Increment i Explanation: The algorithm performs nested loops to compare and swap adjacent elements so that the largest unsorted element moves to its correct position after each pass. 7. What is time complexity? Explain with respect to Bubble, Selection, and Insertion Sort. Answer: Time complexity is the amount of time an algorithm takes to complete based on input size. In Bubble, Selection, and Insertion Sort, all three have nested loops , hence their worst-case time com- plexity is O(n²). Insertion Sort, however, can have a best-case complexity of O(n) if the list is already nearly sorted. 8. Differentiate between swapping and shifting with suitable examples from the sorting algo- rithms. Answer: Swapping Shifting Used in Bubble and Selection Sort. Used in Insertion Sort. Exchanges the positions of two elements. Moves elements one position to the right. Example: list[j], list[j+1] = list[j+1], list[j] Example: list[j+1] = list[j]

SORTING

3. Explain the working of Selection Sort using an example. Show all passes. Answer: Selection Sort selects the smallest element from the unsorted portion and swaps it with the first element in the unsorted list. Example: numList = [8, 7, 13, 1, -9, 4] Pass 1: Minimum is -9 → Swap with 8 → [-9, 7, 13, 1, 8, 4] Pass 2: Minimum is 1 → Swap with 7 → [-9, 1, 13, 7, 8, 4] Pass 3: Minimum is 4 → Swap with 13 → [-9, 1, 4, 7, 8, 13] Pass 4: Already sorted → [-9, 1, 4, 7, 8, 13] Final List: [-9, 1, 4, 7, 8, 13] 4. Write the algorithm and Python program for Selection Sort. Answer: Algorithm 5.2: Selection Sort

  1. Set i = 0
  2. WHILE i < n repeat:
    • Set min = i, flag = 0
    • Set j = i + 1
    • WHILE j < n repeat:
      • IF numList[j] < numList[min]:
        • min = j, flag = 1
      • j = j + 1
    • IF flag = 1 → Swap numList[i], numList[min]
    • i = i + 1 Python Program: def selection_Sort(list 2): n = len(list2)

SORTING

for i in range(n): min = i for j in range(i+ 1 , n): if list2[j] < list2[min]: min = j list2[i], list2[min] = list2[min], list2[i]

5. What is Insertion Sort? Explain its working with an example and diagrammatically. Answer: Insertion Sort builds a sorted list one element at a time. Each new element is inserted into its correct position in the sorted list by shifting larger elements to the right. Example: numList = [8, 7, 13, 1, -9, 4] Pass 1: [7, 8, 13, 1, -9, 4] Pass 2: [7, 8, 13, 1, -9, 4] Pass 3: [1, 7, 8, 13, -9, 4] Pass 4: [-9, 1, 7, 8, 13, 4] Pass 5: [-9, 1, 4, 7, 8, 13] Final List: [-9, 1, 4, 7, 8, 13] 6. Write the algorithm and Python implementation of Insertion Sort. Answer: Algorithm 5.3: Insertion Sort

  1. Set i = 1
  2. WHILE i < n repeat:
    • temp = numList[i]
    • j = i – 1
    • WHILE j 0 and numList[j] > temp repeat:
      • numList[j+1] = numList[j]
      • j = j – 1
    • numList[j+1] = temp
    • i = i + 1 Python Program: def insertion_Sort(list 3): n = len(list3)

SORTING

temp = list3[i] j = i - 1 while j >= 0 and temp < list3[j]: list3[j+ 1 ] = list3[j] j -= 1 list3[j+ 1 ] = temp

7. Compare Bubble Sort, Selection Sort, and Insertion Sort based on working, time complexity, and best use cases. Answer: Criteria Bubble Sort Selection Sort Insertion Sort Basic Operation Swaps adjacent elements Selects minimum and swaps Inserts in sorted portion Time Complexity O(n²) O(n²) O(n²), best case O(n) Best Use Case Small lists Small or fixed-size lists Nearly sorted lists Stable? Yes No Yes 8. What is time complexity? Describe the complexity of the three sorting algorithms discussed in the chapter. Answer: Time complexity is a measure of the amount of time an algorithm takes based on input size. - Bubble Sort: O(n²) – Nested loop for comparisons and swaps - Selection Sort: O(n²) – Regardless of input, comparisons are same - Insertion Sort: O(n²) in worst case, O(n) in best case (nearly sorted data) All three algorithms are quadratic time algorithms due to nested loops. 9. Give the syntax and explanation of swapping and shifting with examples. Answer: Swapping Syntax in Python: list[j], list[j+ 1 ] = list[j+ 1 ], list[j] Example: In Bubble/Selection Sort → swaps adjacent or selected elements.

SORTING

Shifting Syntax: list[j+ 1 ] = list[j] Example: In Insertion Sort → elements are moved one place right to insert a smaller element in the correct position.

10. Explain with an example how you can use Bubble Sort to find the median of a list. Answer: Step 1: Sort the list using Bubble Sort. Step 2: If number of terms is odd, median is the middle term. Step 3: If number is even, median = (term[n//2 – 1] + term[n//2]) / 2 Example: List = [4, 1, 5, 3] → After Bubble Sort: [1, 3, 4, 5] Median = (3 + 4)/2 = **3.

  1. What is the significance of pass number in all sorting algorithms? Explain with examples. Answer:** A pass is a complete iteration over the list.
  • In Bubble Sort , each pass places the largest unsorted element at its correct position.
  • In Selection Sort , each pass selects and places the next smallest element.
  • In Insertion Sort , each pass inserts the next element into the correct position in the sorted list. Example for Bubble Sort (n = 6): 5 passes are needed. 12. Explain how sorting can be useful in real-world applications with examples. Answer: Sorting simplifies and speeds up data retrieval and comparison. Examples:
  • Dictionary words sorted alphabetically
  • Roll numbers arranged in order in an exam hall
  • Student data sorted by height, weight, or scores
  • Percentile calculation in aptitude tests using sorting Sorting is essential before binary search or when evaluating ranks/statistics.

CHAPTER END EXERCISES

1. Consider a list of 10 elements: numList = [7, 11, 3, 10, 17, 23, 1, 4, 21, 5] Display the partially sorted list after three complete passes of Bubble sort.

SORTING

List 2: [11, 7, 5, 3, 2] If the lists are sorted using Insertion Sort then which of the lists (List 1 or List 2) will make the minimum number of comparisons? Justify using diagrammatic representation. Answer:

  • List 1 is already sorted → Best-case scenario
  • Comparisons per pass: 0 (or 1 minimal comparison per element)
  • Time complexity: O(n)
    • List 2 is reverse sorted → Worst-case scenario - Maximum comparisons and shifts per pass - Time complexity: O(n²) Conclusion: List 1 will make the minimum number of comparisons as it represents the best-case input for Insertion Sort. 4. Write a program using user-defined functions that accepts a list of numbers as an argument and finds its median. (Hint: Use bubble sort to sort the accepted list. If there are an odd number of terms, the median is the center term. If even, add the two middle terms and divide by 2 to get the median.) Answer: def bubble_sort(l st): n = len(lst) for i in range(n): for j in range( 0 , n-i- 1 ): if lst[j] > lst[j+ 1 ]: lst[j], lst[j+ 1 ] = lst[j+ 1 ], lst[j] def find_median(l st): bubble_sort(l st) n = len(lst) if n % 2 == 1 : return lst[n// 2 ] else : return (lst[n// 2 - 1 ] + lst[n// 2 ]) / 2 # Example nums = [ 4 , 2 , 7 , 3 ]

SORTING

print("Median is:", find_median(nums)) Output: Median is: 3.

SORTING

Output: 90th Percentile is: 90

6. During admission in a course, the names of the students are inserted in ascending order. Thus, performing the sorting operation at the time of inserting elements in a list. Identify the type of sorting technique being used and write a program using a user-defined function that is invoked every time a name is input and stores the name in ascending order of names in the list. Answer: Type of Sorting Technique: Insertion Sort Python Program:

SORTING

def insert_in_order(name_list, new_name): name_list.append(new_name) i = len(name_list) - 1 while i > 0 and name_list[i] < name_list[i- 1 ]: name_list[i], name_list[i- 1 ] = name_list[i- 1 ], name_list[i] i -= 1 return name_list # Example names = [] names = insert_in_order(names, "Zara") names = insert_in_order(names, "Amit") names = insert_in_order(names, "Meera") print("Sorted Names:", names) Output: Sorted Names: ['Amit', 'Meera', 'Zara']