Insertion Sort [codingblocks]

Given an array A of size N , write a function that implements insertion sort on the array. Print the elements of sorted array.


Input Format
First line contains a single integer N denoting the size of the array. Next line contains N space seperated integers where ith integer is the ith element of the array.

Constraints
1 <= N <= 1000
|Ai| <= 1000000

Output Format
Output N space seperated integers of the sorted array in a single line.

Sample Input
4
3 4 2 1

Sample Output
1 2 3 4

Explanation
For each test case, write insertion sort to sort the array.


Java Code:



/*
Amit Kumar
04-12-2020
IDE Code: https://ide.geeksforgeeks.org/mIraBayPe6
*/
package array;
import java.util.Scanner;

public class Array_InsertionSort {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String [] args) {
        int arrSize = scanner.nextInt();
        int [] arr = new int[arrSize];
        for (int i=0; i<arrSize; i++) {
            arr[i] = scanner.nextInt();
        }

        insertionSort(arr);

        for (int value : arr) {
            System.out.print(value + " ");
        }
    }

    private static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; ++i) {
            int key = arr[i];
            int j = i - 1;

            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
}

Comments

  1. PokerStars PokerStars Review - Goyang Cafe
    PokerStars PokerStars. 사카미치 마루 Rating: 4.5 · 블랙잭전략 ‎Review 식보 by goyangfc.com 안전한 사이트 · ‎Price range: ($) 마틴 게일 전략

    ReplyDelete

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )