You are on page 1of 28

PYTHON PROGRAMMING

(KNC- 302)
UNIT 5 (Continued)

By- Dr. Nidhi Saxena


Asst. Professor
CS Dept.
Sorting
Sort is a term used to describe the process of organizing data in a particular order allowing for
information to be found easier.

In computer science, arranging in an ordered sequence is called "sorting". Sorting is a common


operation in many applications, and efficient algorithms to perform it have been developed.
The most common uses of sorted sequences are:

•making lookup or search efficient;


•making merging of sequences efficient.
•enable processing of data in a defined order.

For example, names and contact information may be sorted in alphabetical order to allow the
person looking for a name to see if it's available.
–Example:
•Contact list on your phone.
•Ordering marks before assignment of grades.
Common sorting algorithms

Bubble/Shell sort: Exchange two adjacent elements if they are out of order. Repeat until array is
sorted.
Insertion sort: Scan successive elements for an out-of-order item, then insert the item in the
proper place.
Selection sort: Find the smallest (or biggest) element in the array, and put it in the proper place.
Swap it with the value in the first position. Repeat until array is sorted.

Quick sort: Partition the array into two segments. In the first segment, all elements are less than
or equal to the pivot value. In the second segment, all elements are greater than or equal to the
pivot value. Finally, sort the two segments recursively.

'Merge sort': Divide the list of elements in two parts, sort the two parts individually and then
merge it.
Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning.

How Selection Sort Works?


Consider the following depicted array as an example.
The algorithm maintains two subarrays in a
given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the


minimum element (considering ascending
order) from the unsorted subarray is picked
and moved to the sorted subarray.

The same process is applied to the


rest of the items in the array.
# Python program for implementation of Selection using
Iterative Method

A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),
# Python program for implementation of Selection using
Recursive Method

def selection(list, i, j, flag):


size = len(list)
if (i < size - 1):
if (flag):
j = i + 1;
if (j < size):
if (list[i] > list[j]):
list[i], list[j] = list[j], list[i]
selection(list, i, j + 1, 0);
selection(list, i + 1, 0, 1);
# print(list)

list = [6, 2, 3, 7, 9, 1, 4, 10, 8, 5]


selection(list, 0, 0, 1)
print(list)
Selection sort
Class Sorting algorithm
Data structure Array
2
Worst-case performance О(n ) comparisons, О(n) swaps
2
Best-case performance О(n ) comparisons, O(1) swaps
2
Average performance О(n ) comparisons, О(n) swaps
Worst-case space complexity O(1) auxiliary
Applications
The applications of Selection Sort is as follows:
•Selection sort almost always outperforms bubble sort and gnome sort.
•Can be useful when memory write is a costly operation.
•While selection sort is preferable to insertion sort in terms of number of
writes (Θ(n) swaps versus Ο(n^2) swaps).
•It almost always far exceeds the number of writes that cycle sort makes, as cycle
sort is theoretically optimal in the number of writes.
•This can be important if writes are significantly more expensive than reads, such as
with EEPROM or Flash memory, where every write lessens the lifespan of the
memory.

Merge Sort
def mergeSort(array):
if len(array) > 1:

# r is the point where the array is divided into two subarrays


r = len(array)//2
L = array[:r]
M = array[r:]

# Sort the two halves


mergeSort(L)
mergeSort(M)

i=j=k=0
# Until we reach either end of either L or M, pick larger among elements L and M and place them in the correct position at A[ p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1

# When we run out of elements in either L or M, pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1

while j < len(M):


array[k] = M[j]
j += 1
k += 1

# Print the array


def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
array = [6, 5, 12, 10, 9, 1] Merge Sort Complexity
mergeSort(array) Worst complexity: n*log(n)
print("Sorted array is: ")
Average complexity: n*log(n)
printList(array)
Best complexity: n*log(n)
Space complexity: n
Applications of Merge Sort
Here are some of the applications of merge sort which are explained below:
Sorting linked lists: Since random access of elements takes much time in case of the
linked list thus Merge Sort provides a quick solution to sort the elements in the linked
list. This also stores the elements in self-made arrays and does not need random
access in the linked list thus it provides a good solution to sort elements in O(nlogn).
Inversion Count Problem: This is a problem where the degree of sorting of elements
are calculated in a list of array. N case array is sorted degree is 0 and in case of
reverse sorted list degree becomes maximum.
Used internal Sorting: The type of sorting required to be done on data that resides in
secondary memory. This is required in case when the amount of data is too large to
fit into the main memory. Since the memory location of data need not be contiguous
in secondary memory thus merge sort is preferred.
Bubble Sort
def bubbleSort(array):

# run loops two times: one for walking throught the array
# and the other for comparison
for i in range(len(array)):
for j in range(0, len(array) - i - 1):

# To sort in descending order, change > to < in this line.


if array[j] > array[j + 1]:

# swap if greater is at the rear position


(array[j], array[j + 1]) = (array[j + 1], array[j])

data = [-2, 45, 0, 11, -9]


bubbleSort(data)
print('Sorted Array in Asc ending Order:')
print(data)
Exploiting Higher Order Functions
•Using higher order functions, we can create a generic sort function
–Can sort in ascending order or descending order
–Can sort any type for which comparison can be defined!
•Add a parameter (comparison function) at relevant places
•Use the given comparison function to compare

Generic Selection Sort


Merging List in Python
List:
Python knows a number of compound data types, used to group together other
values. The most versatile is the list, which can be written as a list of comma-
separated values (items) between square brackets. Lists might contain items of
different types, but usually the items all have the same type.
1.append
•The append method will add an item to the end of the list.
•The length of the list will be increased by 1.
•It will update the original list itself.
•Return type is None.

num1=[1,2,3]
num2=[4,5,6]
num1.append(num2)
print (num1)
#Output:[1, 2, 3, [4, 5, 6]]

2. extend
•The extend method will extend the list by appending all the items from the iterable.
•The length of the list will be increased depends on the length of the iterable.
•It will update the original list itself.
•Return type is None.
num1=[1,2,3]
num2=[4,5,6]
num1.extend(num2)
print (num1)
#Output:[1, 2, 3, 4, 5, 6]
3. Concatenation
•The list also supports concatenation operations.
•We can add two or more lists using + operator.
•It won’t update the original list.
•Return type is a new list object.
Example 1:Concatenating two lists
num1=[1,2,3]
num2=[4,5,6]
num3=num1+num2
print (num3)
#Output:[1, 2, 3, 4, 5, 6]

Example 2:Concatenating two or more lists


num1=[1,2,3]
num2=[4,5,6]
num3=[7,8]
num4=[9,10]
num5=num1+num2+num3+num4
print (num5)
#Output:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4. Unpacking
An asterisk * denotes iterable unpacking. Its operand must be iterable. The iterable is expanded into a
sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
list1=[*list2,*list3]
First, it will unpack the contents and then create a list from its contents.
num1=[1,2,3]
num2=[4,5,6]
num3=[*num1,*num2]
print (num3)
#Output:[1, 2, 3, 4, 5, 6]

5. itertools.chain
Makes an iterator that returns an element from the first iterable until its exhausted, then proceeds to
the next iterable. It will treat consecutive sequences as a single sequence.
itertools.chain(*iterables)

The list is also iterable, so we can use itertools.chain() to merge two dictionaries. The return type will
be itertools.chain object. We can convert to a list using the list() constructor.
import itertools
num1=itertools.chain([1,2,3],[4,5,6])
#Returns an iterator object

print (num1)#Output:<itertools.chain object at 0x029FE4D8>


#converting iterator object to list object
print(list(num1))#Output:[1, 2, 3, 4, 5, 6]
6. List comprehension.
A list comprehension consists of brackets[] containing an expression followed by a for clause, then zero
or more for or if clauses. The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses that follow it.
[expression for item in iterable if conditional]
Example 1.Joining two lists using list comprehension
num1=[1,2,3]
num2=[4,5,6]
num3=[x for n in (num1,num2) for x in n]
print (num3)#Output:[1, 2, 3, 4, 5, 6]

7. for loop
•First for loop to go through the lists. (for n in (num1,num2)
•Second for loop to go through the elements in the list. (for x in n)
•Then it will append each element to the empty list created before num3
num1=[1,2,3]
num2=[4,5,6]
num3=[]
for n in (num1,num2):
for x in n:
num3.append(x)
print (num3)
#Output:[1, 2, 3, 4, 5, 6]
How to join all strings in a list:
str.join(iterable)
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are
any non-string values in iterable, including bytes objects. The separator between elements is the string
providing this method.
Example 1: Joining all strings in the list. The separator is given as space.
num1=["Welcome", "to", "python", "programming", "language"]
num2=" ".join(num1)
print (num2)
#Output:Welcome to python programming language

Example 2: Joining all strings in the list. The separator is given as -


num1=["1","2","3"]
num2="-".join(num1)
print (num2)
#Output:1-2-3
How to remove duplicate elements while merging two lists.
Python sets don’t contain duplicate elements.
To remove duplicate elements from lists we can convert the list to set using set() and then convert back
to list using list() constructor.
num1=[1,2,3,4,5]
num2=[1,3,5,7,9]
num3=list(set(num1+num2))
print (num3)
#Output:[1, 2, 3, 4, 5, 7, 9]

You might also like