0% found this document useful (0 votes)
87 views11 pages

DSA Lab 5

The document provides instructions for a lab session on sorting techniques using Python. It discusses quick sort and merge sort algorithms. For quick sort, it explains the partitioning process and time complexity. For merge sort, it describes the divide and conquer approach and merging process. The objectives are to implement quick sort and merge sort to arrange lists of integers in ascending order. Students are given tasks to apply the sorting algorithms to sample data and modify the code for descending order sorts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views11 pages

DSA Lab 5

The document provides instructions for a lab session on sorting techniques using Python. It discusses quick sort and merge sort algorithms. For quick sort, it explains the partitioning process and time complexity. For merge sort, it describes the divide and conquer approach and merging process. The objectives are to implement quick sort and merge sort to arrange lists of integers in ascending order. Students are given tasks to apply the sorting algorithms to sample data and modify the code for descending order sorts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

LAB 05

SORTING TECHNIQUES USING


PYTHON

STUDENT NAME ROLL NO SEC

SIGNATURE & DATE

MARKS AWARDED:

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING


SCIENCE (NUCES) KARACHI

Prepared by: Engr. Syed Asim Mahmood Summer 2022


[SORTING TECHNIQUES USING PYTHON] LAB: 05

Lab Session 05: SORTING TECHNIQUES USING PYTHON


OBJECTIVES:
1. Implementing Quick sort technique to arrange a list of integers in ascending order.

2. Implementing merge sort technique to arrange a list integers in ascending order

Quick Sort:
This divide and conquer algorithm is the most often used sorting algorithm covered in
this article. When configured correctly, it's extremely efficient and does not require the extra
space Merge Sort uses. We partition the list around a pivot element, sorting values around the
pivot.

Explanation
Quick Sort begins by partitioning the list - picking one value of the list that will be in
its sorted place. This value is called a pivot. All elements smaller than the pivot are moved to
its left. All larger elements are moved to its right.

Knowing that the pivot is in its rightful place, we recursively sort the values around
the pivot until the entire list is sorted. Quick sort is also a divide and conquer algorithm like merge
sort. Although it’s a bit more complicated, in most standard implementations it performs
significantly faster than merge sort and rarely reaches its worst case complexity of O (n²).

It has 3 main steps:

1. We first select an element which we will call the pivot from the array.

2. Move all elements that are smaller than the pivot to the left of the pivot; move all
elements that are larger than the pivot to the right of the pivot. This is called the partition
operation.

3. Recursively apply the above 2 steps separately to each of the sub-arrays of elements
with smaller and bigger values than the last pivot.
def partition(nums, low, high):
# We select the middle element to be the pivot. Some implementations select
# the first element or the last element. Sometimes the median value
becomes # the pivot, or a random one. There are many more strategies that
can be
# chosen or created.
pivot = nums [(low + high) //
2] i = low – 1
j = high + 1

National University of Computer & Emerging Sciences, Karachi


Page | 1
LAB: 05 [SORTING TECHNIQUES USING PYTHON]

while True:
i += 1
while nums[i] < pivot:
i += 1

j -= 1
while nums[j] > pivot:
j -= 1

if i >= j:
return j

# If an element at i (on the left of the pivot) is larger than the element at j
(on right right of the pivot), then swap them

nums[i], nums[j] = nums[j], nums[i]

def quick_sort(nums):
# Create a helper function that will be called recursively
def _quick_sort(items, low, high):
if low < high:
# This is the index after the pivot, where our lists are split
split_index = partition(items, low, high)
_quick_sort(items, low, split_index)
_quick_sort(items, split_index + 1, high)

_quick_sort(nums, 0, len(nums) - 1)

# MAIN CODE
random_list_of_nums = [22, 5, 1, 18,
99] quick_sort(random_list_of_nums)
print(random_list_of_nums)
Time Complexity:
The worst case scenario is when the smallest or largest element is always selected as
the pivot. This would create partitions of size n-1, causing recursive calls n-1 times. This
leads us to a worst case time complexity of O(n^2).

While this is a terrible worst case, Quick Sort is heavily used because its average time
complexity is much quicker. While the partition function utilizes nested while loops, it does
comparisons on all elements of the array to make its swaps. As such, it has a time complexity
of O(n).
With a good pivot, the Quick Sort function would partition the array into halves which
grows logarithmically with n. Therefore the average time complexity of the Quick Sort
algorithm is O(nlog(n)).

Page | 2 National University of Computer & Emerging Sciences, Karachi


[SORTING TECHNIQUES USING PYTHON] LAB: 05

Merge sort:
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves,
calls itself for the two halves and then merges the two sorted halves. The merge () function
is used for merging two halves. The merge (arr, l, m, r) is key process that assumes that
arr [l..m] and arr [m+1..r] are sorted and merges the two sorted sub- arrays into one.

National University of Computer & Emerging Sciences, Karachi Page | 3


LAB: 05 [SORTING TECHNIQUES USING PYTHON]

Merge sort is a perfectly elegant example of a Divide and Conquer algorithm. It


simple uses the 2 main steps of such an algorithm:
1. Continuously divide the unsorted list until you have N sublists, where
each sublist has 1 element that is “unsorted” and N is the number of elements in
the original array.
2. Repeatedly merge i.e conquer the sublists together 2 at a time to produce
new sorted sublists until all elements have been fully merged into a single sorted
array.

Code:

def merge(left_list, right_list):


sorted_list = [ ]
left_list_index = right_list_index = 0

# We use the list lengths often, so its handy to make variables


left_list_length, right_list_length = len(left_list), len(right_list)

for _ in range(left_list_length + right_list_length):


if left_list_index < left_list_length and right_list_index < right_list_length:
# We check which value from the start of each list is smaller
# If the item at the beginning of the left list is smaller, add it
# to the sorted list
if left_list[left_list_index] <= right_list[right_list_index]:
sorted_list.append(left_list[left_list_index]) left_list_index +=
1 # If the item at the beginning of the right list is smaller, add it
# to the sorted list
else: sorted_list.append(right_list[right_list_index])
right_list_index += 1

# If we've reached the end of the of the left list, add the elements
# from the right list
elif left_list_index == left_list_length:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
# If we've reached the end of the of the right list, add the elements
# from the left list
elif right_list_index == right_list_length:
sorted_list.append(left_list[left_list_index])
left_list_index += 1

return sorted_list

Page | 4 National University of Computer & Emerging Sciences, Karachi


[SORTING TECHNIQUES USING PYTHON] LAB: 05

def merge_sort(nums):
# If the list is a single element, return it
if len(nums) <= 1:
return nums

# Use floor division to get midpoint, indices must be integers


mid = len(nums) // 2

# Sort and merge each half


left_list =
merge_sort(nums[:mid])
right_list = merge_sort(nums[mid:])

# Merge the sorted lists into a new


one return merge(left_list, right_list)

# Verify it works
random_list_of_nums = [120, 45, 68, 250, 176]
random_list_of_nums =
merge_sort(random_list_of_nums)
Note that the merge_sort() function, unlike the previous sorting algorithms, returns a
new list that is sorted, rather than sorting the existing list. Therefore, Merge Sort
requires space to create a new list of the same size as the input list.

Lab tasks

1. Apply the quick sort on the following elements 21, 11, 5, 78, 49, 54, 72, 88.

2. Make a code for quick sort that sorts in descending order?

3. Apply the merge sort on the following elements 21, 11, 5, 78, 49, 54, 72, 88, 56, 28, 10.

4. Make a code for merge sort that sorts in descending order?

National University of Computer & Emerging Sciences, Karachi Page | 5


LAB: 05 [FALL 2021 - DSA LAB] [SORTING TECHNIQUES USING PYTHON]

Lab Report:
(It is recommended to write Lab Report in bullet Form)

Page | 6 National University of Computer & Emerging Sciences, Karachi Instructor: Misbah Malik
[SORTING TECHNIQUES USING PYTHON] LAB: 05

Student Name(s): Roll:


Section:

Method: Lab reports and instructor observation during Lab sessions Outcome
Assessed:
a. Ability to conduct experiments, as well as to analyze and interpret data (P3/PLO 4).
b. Ability to function on multi-disciplinary teams (A/PLO 9).
c. Ability to use the techniques, skills, and modern engineering tools necessary for engineering
practice (P/PLO 5).
d. An ability to design a solution for an open-ended lab with appropriate considerations for public health
and safety, cultural, societal, and environmental factors. (C/PLO3)

Performance Exceeds expectation (5-4) Meets expectation (3-2) Does not meet expectation Marks
(1-0)

1. Realization of Selects relevant equipment to the Needs guidance to select relevant Incapable of selecting relevant
Experiment [a, c] experiment, develops setup equipment to the experiment and equipment to conduct the
diagrams of equipment to develop equipment connection experiment, equipment connection
connections or wiring. or wiring diagrams. or wiring diagrams.

2. Teamwork [b] Actively engages and Cooperates with other group Distracts or discourages other
cooperates with other group members in a reasonable manner. group members from conducting
members in an the experiment.
effective manner.

3. Conducting Does proper calibration of Calibrates equipment, examines Unable to calibrate appropriate
Experiment [a, c] equipment, carefully examines equipment moving parts, and operatesequipment, and equipment operation
equipment moving parts, and the equipment with minor error. is substantially wrong.
ensures smooth operation and
process.
4. Laboratory Respectfully and carefully observes Observes safety rules and procedures Disregards safety rules and
Safety Rules [a] safety rules and procedures with minor deviation. procedures.

5. Data Collection Plans data collection to achieve Plans data collection to achieve Does not know how to plan data
[a] experimental objectives, and experimental objectives, and collects collection to achieve experimental
conducts an orderly and a complete complete data with minor error. goals; data collected is incomplete and
data collection. contain errors.
6. Data Analysis [a] Accurately conducts simple Conducts simple computations and Unable to conduct simple statistical
computations and statistical analysis statistical analysis using collected dataanalysis on collected data; no attempt
using collected data; correlates with minor error; reasonably correlatesto correlate experimental results with
experimental results to known experimental results to knownknown theoretical values; incapable of
theoretical values; accounts for theoretical values; attempts to accountexplaining measurement errors or
measurement errors and parameters for measurement errors and parametersparameters that affect the
that affect experimental results. that affect experimental results. experimental results.

7. Design of Able to design and implement the Able to design and partially implement Unable to design the complete
Experiment [d] complete solution of open-ended the complete solution of open-ended solution of open-ended problem with
problem with safety, health and problem with safety, health and safety, health and environment related
environment related considerations. environment related considerations. considerations.

Total

Lecturer / Faculty

Signature:

Date:

National University of Computer & Emerging Sciences, Karachi Page | 7


Q1
def quick_sort(arr,left,right):
if left<right:
partition_pos=partition(arr,left,right)
quick_sort(arr,left,partition_pos-1)
quick_sort(arr,partition_pos+1,right)
def partition(arr,left,right):
i=left
j=right-1
pivot=arr[right]
while i<j:
while i<right and arr[i]<pivot:
i+=1
while j>left and arr[j]>=pivot:
j-=1
if i<j:
arr[i],arr[j]=arr[j],arr[i]
if arr[i]>pivot:
arr[i],arr[right]=arr[right],arr[i]
return i
z=[21,11,5,78,49,54,72,88]
quick_sort(z,0,len(z)-1)
print (z)

Q2
def partition(array, begin, end):
pivot_idx = begin
for i in range(begin+1, end+1):
if array[i] >= array[begin]:
pivot_idx += 1
array[i], array[pivot_idx] = array[pivot_idx], array[i]
array[pivot_idx], array[begin] = array[begin], array[pivot_idx]
return pivot_idx

def quick_sort_recursion(array, begin, end):


if begin >= end:
return
pivot_idx = partition(array, begin, end)
quick_sort_recursion(array, begin, pivot_idx-1)
quick_sort_recursion(array, pivot_idx+1, end)

def quick_sort(array, begin=0, end=None):


if end is None:
end = len(array) - 1

return quick_sort_recursion(array, begin, end)


z=[21,11,5,78,49,54,72,88]
quick_sort(z)
print(z)

Q3
def merge(left_list, right_list):
sorted_list = [ ]
left_list_index = right_list_index = 0
left_list_length, right_list_length = len(left_list), len(right_list)
for _ in range(left_list_length + right_list_length):
if left_list_index < left_list_length and right_list_index < right_list_length:
if left_list[left_list_index] <= right_list[right_list_index]:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
else:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif left_list_index == left_list_length:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif right_list_index == right_list_length:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
return sorted_list
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left_list = merge_sort(nums[:mid])
right_list = merge_sort(nums[mid:])
return merge(left_list, right_list)

random_list_of_nums = [21, 11, 5, 78, 49, 54,72, 88, 56, 28,10]


random_list_of_nums = merge_sort(random_list_of_nums)
print(random_list_of_nums)

Q4
def merge(left_list, right_list):
sorted_list = [ ]
left_list_index = right_list_index = 0
left_list_length, right_list_length = len(left_list), len(right_list)
for _ in range(left_list_length + right_list_length):
if left_list_index < left_list_length and right_list_index < right_list_length:
if left_list[left_list_index] >= right_list[right_list_index]:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
else:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif left_list_index == left_list_length:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif right_list_index == right_list_length:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
return sorted_list
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left_list = merge_sort(nums[:mid])
right_list = merge_sort(nums[mid:])
return merge(left_list, right_list)

random_list_of_nums = [21, 11, 5, 78, 49, 54,72, 88, 56, 28,10]


random_list_of_nums = merge_sort(random_list_of_nums)
print(random_list_of_nums)

You might also like