Insertion sort Read in a sequence of 32bit signed integers o

Insertion sort Read in a sequence of 32-bit signed integers (one per line). The first line contains a value n, which is not part of the sequence, indicating how many further lines of integers need to be sorted. Implement insertion sort on an array to output the sequence in increasing sort (numerical) order, count the number of moves required for the sort and how many additional inversions would be needed to reach the maximum number of inversions for the given input and size. (implement in python or java )

Example input

3
7
1
2
which produces output

1

2

7

Solution

public class Sorting {

public static void main(String[] args) {

int ar[], br[];

int i,index;

System.out.println(“Enter the elements you want to be sorted and the first element being the number of elements”);

Scanner s = new Scanner(System.in);

while(s.nextInt())

{i = s.nextInt();

ar[] = i;

}

for (int i=0, j=0;i<ar.length;i++)

{

index = ar[0];

br[j]= br[i+1];

}

insertionSort(br,index);

    }

private static void printNumbers(int[] br) {

for (int i = 0; i < br.length; i++) {

            System.out.print(br[i] + \", \");

        }

        System.out.println(\"\ \");

    }

public static void insertionSort(int array[],int size) {

        int n = array.length;

int count = 0;

        for (int j = 1; j < n; j++) {

            int key = array[j];

            int i = j-1;

            while ( (i > -1) && ( array [i] > key ) ) {

                array [i+1] = array [i];

                i--;

count++;

            }

            array[i+1] = key;

            printNumbers(array);

System.out.println(\"Number of inversions required\", count);

        }

    }

}

Insertion sort Read in a sequence of 32-bit signed integers (one per line). The first line contains a value n, which is not part of the sequence, indicating how
Insertion sort Read in a sequence of 32-bit signed integers (one per line). The first line contains a value n, which is not part of the sequence, indicating how

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site