 Counting Inversions (Swaps) in Insertion Sort Algorithm

Subject Computer Science Data Structures and Algorithms

Question

Let A[l..n] be an array of n distinct numbers. If i < j and A[i] > A[j], then the pair (i, j) is called an inversion of A.
a) Show the insertion sort algorithm. Explain clearly how it works.
b) Modify the insertion sort algorithm to count the number of inversions in the input array.
c) Trace your algorithm for question b above as it counts the number of inversions in this array: [40, 30, 20, 10].

Solution Preview

This material may consist of step-by-step explanations on how to solve a problem or examples of proper writing, including the use of citations, references, bibliographies, and formatting. This material is made available for the sole purpose of studying and learning - misuse is strictly forbidden.

a) In pseudo-code, the Insertion Sort algorithm can be represented like below (two nested loops):

swaps=0
for j = 1 to array.size do
{aux= array[j]    //temporary variable used for swapping the compared items
//the item array[j] is inserted into sorted sub-array array[1 . . j − 1]
i = j − 1
While (i > 0) and (array[i] > aux) do
{array[i +1] = array[i]...

This is only a preview of the solution. Please use the purchase button to see the entire solution

Related Homework Solutions

Arrays, Linked Lists, Queue and Stack Data Structures in C++ \$40.00
Algorithm
Array
List
Queue
Stack
Data
Structure
C++
Singly
Doubly
Prototype
Template
Function
Computer
Science
Function Asymptotic Growth & Basic Java Programming Questions \$15.00
Asymptotic
Growth Rate
Java
Main
Maryland
State
Method
Output
Class
Extends
Computer Science
Data Structures
Algorithms
Computer Engineering Questions \$4.00
Computer Science
Engineering
Intel 8086
Systems
DRAM Memory
RAS
Processors
States
Writing
Propagation
Data Paths
Time Requirements
Clocking Rate
Access Time
Computer Science - Algorithm Assignment \$25.00
Algorithm
Computer Science
Dynamic Programming
Longest Increasing Subsequence
Array
Sorting Algorithms in Java \$33.00
Computer Science
Programming
Insertion Sort
Shellsort
Heapsort
Quicksort
Input Data
Execution Time
Loops
Variables
Statements
Sequences
Functions
Java
Random Values
Input
Output
Live Chats