JOC
JOC
[END OF LOOP]
Step 4: EXIT
SET pos = j
[END OF if]
[END OF LOOP]
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted.
Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element,
then move to the next element. Else, shift greater elements in the array towards
the right.
Program of Insertion Sort
def insertionsort(arr):
for i in range(1 , len(arr)):
key = arr[i]
j = i-1
def printArray(arr):
for i in range( len(arr)):
print ( arr [i] , end = “ “)
print()
If_name_==“_main_”:
arr = [ 12 ,11, 13, 5, 6 ]
insertionSort(arr)
printArray(arr)
Merge Sort
• Merge sort is similar to the quick sort algorithm as it uses the divide
and conquer approach to sort the elements.
• It is one of the most popular and efficient sorting algorithm. It divides
the given list into two equal halves, calls itself for the two halves and
then merges the two sorted halves. We have to define
the merge() function to perform the merging.
• The sub-lists are divided again and again into halves until the list
cannot be divided further.
• Then we combine the pair of one element lists into two-element lists,
sorting them in the process. The sorted two-element pairs is merged
into the four-element lists, and so on until we get the sorted list.
Algorithm of Merge Sort
MERGE_SORT(arr, beg, end)
END MERGE_SORT
Program of Merge sort
def merge_sort(arr):
if len(arr) <= 1:
return arr
# Divide
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
# Merge
return merge(left_half, right_half)
def merge(left, right):
sorted_arr = []
i=j=0
# Compare elements and merge
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_arr.append(left[i])
i += 1
else:
sorted_arr.append(right[j])
# Add remaining elements
sorted_arr.extend(left[i:])
sorted_arr.extend(right[j:])
return sorted_arr
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print(sorted_arr)
begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort
Program of Bubble Sort
def bubble_sort(arr):
n = len(arr)
return arr
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = bubble_sort(arr)
print(sorted_arr)