Lecture 1 Sorting I¶
Selection Sort¶
Given an array of N integers, write a program to implement the Selection sorting algorithm.
Example 1:
Input: N = 6, array[] = {13,46,24,52,20,9}
Output: 9,13,20,24,46,52
Explanation: After sorting the array is: 9, 13, 20, 24, 46, 52
Example 2:
Input: N=5, array[] = {5,4,3,2,1}
Output: 1,2,3,4,5
Explanation: After sorting the array is: 1, 2, 3, 4, 5
Approach 1¶
- Take the smallest and replace with i
In [1]:
def selection_sort(nums):
n = len(nums)
for i in range(n-1):
for j in range(i+1,n):
if nums[j] < nums[i]:
nums[i],nums[j] = nums[j],nums[i]
return nums
print(selection_sort([13,46,24,52,20,9]))
print(selection_sort([5,4,3,2,1]))
[9, 13, 20, 24, 46, 52] [1, 2, 3, 4, 5]
complexity analysus¶
- O(N^2) : N = len(nums)
- O(1)
Bubble Sort¶
Given an array of N integers, write a program to implement the Bubble sorting algorithm.
Example 1:
Input: N = 6, array[] = {13,46,24,52,20,9}
Output: 9,13,20,24,46,52
Explanation: After sorting the array is: 9, 13, 20, 24, 46, 52
Example 2:
Input: N=5, array[] = {5,4,3,2,1}
Output: 1,2,3,4,5
Explanation: After sorting the array is: 1, 2, 3, 4, 5
Approach 1¶
- just keep swapping left and right
- once there are not swaps , it means sorted
In [4]:
def bubble_sort(nums):
n = len(nums)
for i in range(n):
swapped = False
for j in range(n-1):
if nums[j] > nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
swapped = True
if not swapped:
return nums
return nums
print(bubble_sort([13,46,24,52,20,9]))
print(bubble_sort([5,4,3,2,1]))
[9, 13, 20, 24, 46, 52] [1, 2, 3, 4, 5]
complexity analysus¶
- O(N^2) : N = len(nums)
- O(1)
Insertion Sort¶
Given an array of N integers, write a program to implement the Insertion sorting algorithm.
Example 1:
Input: N = 6, array[] = {13,46,24,52,20,9}
Output: 9,13,20,24,46,52
Explanation: After sorting the array is: 9, 13, 20, 24, 46, 52
Example 2:
Input: N=5, array[] = {5,4,3,2,1}
Output: 1,2,3,4,5
Explanation: After sorting the array is: 1, 2, 3, 4, 5
Approach 1¶
- assume first element is sorted
- not insert the elements from 1 to n to correct sorted position
In [6]:
def insertion_sort(nums):
n = len(nums)
for i in range(1,n):
j = i-1
while j>=0 and nums[j+1] < nums[j]:
nums[j+1],nums[j] = nums[j],nums[j+1]
j-=1
return nums
print(insertion_sort([13,46,24,52,20,9]))
print(insertion_sort([5,4,3,2,1]))
[9, 13, 20, 24, 46, 52] [1, 2, 3, 4, 5]
complexity analysus¶
- O(N^2) : N = len(nums)
- O(1)