

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find out the number of shifts required to sort an array using insertion sort in python
Suppose we are given an array and asked to perform insertion sort on it. In insertion sort, each element in an array is shifted to its correct position in the array. We have to find out the total number of shifts required to sort an array. The total number of shifts is an integer number and if the array is already sorted, we return 0.
So, if the input is like input_array = [4, 5, 3, 1, 2], then the output will be 8
[4, 5, 3, 1, 2] = 0 shifts [4, 5, 3, 1, 2] = 0 shifts [3, 4, 5, 1, 2] = 2 shifts [1, 3, 4, 5, 2] = 3 shifts [1, 2, 3, 4, 5] = 3 shifts
total number of shifts are = 0 + 0 + 2 + 3 + 3 = 8.
To solve this, we will follow these steps −
- length := size of input_arr
- temp_arr := a new list of size 1000001 initialized with 0s
- ans := 0
- for each item in input_arr, do
- val := item
- while val > 0, do
- ans := ans + temp_arr[val]
- val := val - (val AND -val)
- val := item
- while val <= 1000000, do
- temp_arr[val] := temp_arr[val] + 1
- val := val + (val AND -val)
- ans := length * (floor value of (length - 1) / 2) - ans
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(input_arr): length = len(input_arr) temp_arr = [0] * 1000001 ans = 0 for item in input_arr: val = item while val > 0: ans += temp_arr[val] val -= val & -val val = item while val <= 1000000: temp_arr[val] = temp_arr[val] + 1 val += val & -val ans = length * (length - 1) // 2 - ans return ans print(solve([4, 5, 3, 1, 2]))
Input
[4, 5, 3, 1, 2]
Output
8
- Related Questions & Answers
- Program to find expected number of shuffle required to sort the elements of an array in Python
- Program to find number of swaps required to sort the sequence in python
- Insertion Sort in Python Program
- Minimum number of swaps required to sort an array in C++
- Python Program for Insertion Sort
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
- Python Program for Binary Insertion Sort
- Python Program for Recursive Insertion Sort
- C program to sort an array by using merge sort
- Java program to implement insertion sort
- C++ Program to Implement Insertion Sort
- Insertion Sort
- Write a Golang program to sort an array using Bubble Sort
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
- C++ Program Recursive Insertion Sort
Advertisements