• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Insertion Sort Advanced Analysis – HackerRank Solution

Insertion Sort Advanced Analysis - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 24, 2022
Reading Time: 1 min read
1
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Insertion Sort Advanced Analysis – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Insertion Sort Advanced Analysis HackerRank Solution
  • Java Insertion Sort Advanced Analysis HackerRank Solution
  • Python 3 Insertion Sort Advanced Analysis HackerRank Solution
  • Python 2 Insertion Sort Advanced Analysis HackerRank Solution
  • C Insertion Sort Advanced Analysis HackerRank Solution
      • Related posts:

Insertion Sort Advanced Analysis – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

 

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

 

C++ Insertion Sort Advanced Analysis HackerRank Solution

Copy Code Copied Use a different Browser

#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<set>
#include<list>
#include<stack>
#include<sstream>
#include<fstream>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cassert>
#define CLRM(x) memset(x,-1,sizeof(x))
#define CLR(x) memset(x,0,sizeof(x))
#define ALL(x) x.begin(),x.end()
#define GI(x) scanf("%d", &x);
#define FORN(i, n) for(int i = 0; i < n; i++)
#define FOR(i, start, end) for(int i = start; i < end; i++)
#define PB push_back
#define MP make_pair
#define VI vector<int> 
#define VVI vector<vector<int> >
#define PII pair<int,int>
#define SZ(x) (int)x.size()
#define LL long long
#define MIN(a,b) (a)<(b)?(a):(b)
#define MAX(a,b) (a)>(b)?(a):(b)
#define LMAX 1000000000000000000LL
#define IMAX 1000000000
using namespace std;

#define MAXN 110000
int N;
int d[MAXN];

LL mergesort(int low, int high)
{
	if(low >= high)
		return 0;
	
	int mid = (low+high)/2;

	LL ret = 0;
	ret = mergesort(low, mid) + mergesort(mid+1, high);
	vector<int> v;
	int i, j, k;
	i = low; j = mid + 1;
	while(i <= mid && j <= high)
	{
		if(d[i] > d[j])
		{
			v.PB(d[j]);
			ret+=(LL)(mid-i+1);
			j++;
		}
		else
		{
			v.PB(d[i]);
			i++;
		}
	}
	while(i <= mid)
	{
		v.PB(d[i]);
		i++;
	}
	while(j <= high)
	{
		v.PB(d[j]);
		j++;
	}
	for(i = 0; i < v.size(); i++)
	{
		d[i + low] = v[i];
	}
	return ret;
}
LL solve()
{
	LL ret = mergesort(0, N-1);
	return ret;
}
int main()
{
	int tes;
	GI(tes);
	while(tes--)
	{
		int i;
		GI(N);
		FORN(i, N)
		{
			GI(d[i]);
		}
		LL ans = solve();
		printf("%lld\n", ans);
	}
	return 0;
}

Java Insertion Sort Advanced Analysis HackerRank Solution

Copy Code Copied Use a different Browser

import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lwc626
 */
public class Solution {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		MyInputReader in = new MyInputReader(inputStream);
		MyOutputWriter out = new MyOutputWriter(outputStream);
		Insertion_Sort solver = new Insertion_Sort();
		int testCount = Integer.parseInt(in.next());
		for (int i = 1; i <= testCount; i++)
			solver.solve(i, in, out);
		out.close();
	}
}

class Insertion_Sort {
	public void solve(int testNumber, MyInputReader in, MyOutputWriter out) {
        int n = in.nextInt() ;
        int[] A = new int[ n ] ;
        IOUtils.readIntArrays(in, A);
        out.printLine( reverse_pair(out,A, 0 , n-1) );
	}

    private long reverse_pair(MyOutputWriter out,int[] a , int l , int r) {
        if( l == r ) return 0 ;
        int m = ( l + r ) / 2 ;
        long ret = reverse_pair( out,a , l , m ) ;
        ret += reverse_pair( out,a , m+1 , r ) ;

        //out.printLine( l , r );
        //IOUtils.printIntArrays(out , a );
        int [] tmp = new int[ r - l + 1];
        int nl = l , nr = m+1 , n = 0;
        while ( nl <= m && nr <= r ){
            if( a[nl] <= a[nr] ){
                tmp[n++] = a[nl++] ;
                ret += nr - m -1 ;
            }else{
                tmp[n++] = a[nr++] ;
            }
        }
        while ( nl <= m ) { tmp[ n ++ ] = a[ nl ++ ]; ret += nr-m-1;}
        while ( nr <= r ) tmp[ n ++ ] = a[ nr ++ ];
        System.arraycopy( tmp , 0 , a , l, n );
        return ret;
    }
}

class MyInputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

    public MyInputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
    
    }

class MyOutputWriter {
    private final PrintWriter writer;

    public MyOutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public MyOutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object...objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}

class IOUtils {
    public static void readIntArrays( MyInputReader in,int[]... arrays ){
        for(int i = 0 ; i < arrays[0].length; i++ )
            for( int j = 0 ; j < arrays.length ; j ++ )
                arrays[j][i] = in.nextInt();
    }
    }

Python 3 Insertion Sort Advanced Analysis HackerRank Solution

Copy Code Copied Use a different Browser

#!/bin/python3

import math
import os
import random
import re
import sys
from bisect import bisect_left as lower_bound

# Complete the insertionSort function below.
def insertionSort(arr):
    n=len(arr)
    def BIT_update(BITTree,n,i,v):
        while i<=n:
            BITTree[i]+=v
            i+=i&(-i)

    def BIT_getSum(BITTree,i):
        s=0
        while i>0:
            s+=BITTree[i]
            i-=i&(-i)
        return s
    def convert(arr, n): 
   
        temp = [0]*(n) 
        for i in range(n): 
            temp[i] = arr[i] 
        temp = sorted(temp) 
  
        for i in range(n):  
            arr[i] = lower_bound(temp, arr[i]) + 1

    def getInvCount(arr, n): 
        invcount = 0
        convert(arr,n)   
        BIT = [0] * (n + 1)  
        for i in range(n - 1, -1, -1):   
            invcount += BIT_getSum(BIT, arr[i] - 1)  
            BIT_update(BIT, n, arr[i], 1)  
        return invcount
    return getInvCount(arr,n)


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        n = int(input())

        arr = list(map(int, input().rstrip().split()))

        result = insertionSort(arr)

        fptr.write(str(result) + '\n')

    fptr.close()

Python 2 Insertion Sort Advanced Analysis HackerRank Solution

Copy Code Copied Use a different Browser

# Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(raw_input())
for t in range(0, T):
    N = int(raw_input())
    a = [0] * 1000001
    res = 0
    line = raw_input()
    for item in line.split(' '):
        x = int(item)
        while x > 0:
            res += a[x]
            x -= x & -x
        x = int(item)
        while x <= 1000000:
            a[x] = a[x] + 1
            x += x & -x
    res = N * (N - 1) / 2 - res
    print res

C Insertion Sort Advanced Analysis HackerRank Solution

Copy Code Copied Use a different Browser

#include<stdio.h>
int d[100001],n;
int temp[100001];
long long ans;
void merge(int L1,int U1,int L2,int U2)
{
	int p,q,j,i;
	p=L1;q=L2;i=0;
	while(p<=U1 && q<=U2)
	{
		if(d[p]<=d[q])
		{
			temp[i++]=d[p++];
		}
		else
		{
			ans=(long long)ans+U1-p+1;
			temp[i++]=d[q++];
		}
	}
	for(;p<=U1;)
	{
		temp[i++]=d[p++];
	}
	for(;q<=U2;)
	{
		temp[i++]=d[q++];
	}
	for(q=L1,i=0;q<=U1;q++,i++)
	{
		d[q]=temp[i];
	}
	for(q=L2,j=i;q<=U2;q++,j++)
	{
		d[q]=temp[j];
	}
}

void process(int LB, int UB)
{
	int m;
	if(UB>LB)
	{
		m=(LB+UB)/2;
		process(LB,m);
		process(m+1,UB);
		merge(LB,m,m+1,UB);
	}
}

int getnum()
{
	int tmp=0;
	char ch;
	while(1)
	{
		ch=getchar();
		if(ch>='0'&&ch<='9')
		{
			tmp*=10;
			tmp+=ch-48;
		}
		else break;
	}
	return tmp;
}
int main()
{
	int t,i,j;
	//scanf("%d",&t);
	t=getnum();
	while(t--)
	{
		//scanf("%d",&n);
		n=getnum();
		for(i=1;i<=n;i++)
			d[i]=getnum();
		ans=0;
		process(1,n);
		printf("%lld\n",ans);
	}
	return 0;
}

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionCount Strings – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionString Function Calculation – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAshton and String – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionString Similarity – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFind Strings – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPalindromic Border – HackerRank Solution
Tags: Cfull solutionHackerRank SolutionInsertion Sort Advanced Analysisjavajava 8Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Morgan and a String - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Count Strings - HackerRank Solution

Comments 1

  1. Pingback: Solutions of Algorithms Data Structures Hard HackerRank - Zeroplusfour

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionCount Strings – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionString Function Calculation – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAshton and String – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionString Similarity – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFind Strings – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPalindromic Border – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Clues on a Binary Path – HackerRank Solution

May 31, 2022
208
Halloween Countdown to 31st october 2022
Countdowns

Halloween Countdown to 31st october 2022

May 8, 2022
1
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Weather Observation Station 5 EasySQL (Intermediate) – SQL – HackerRank Solution

May 30, 2022
0
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

A Super Hero – HackerRank Solution

May 31, 2022
11

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?