Insertion Sort – Part 2 in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank, Algorithm Solutions of Problem Solving Section in Java. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Insertion Sort – Part 2 in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Introduction To Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results. 

Advantages of Algorithms:

  • It is easy to understand.
  • Algorithm is a step-wise representation of a solution to a given problem.
  • In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Link for the ProblemInsertion Sort – Part 2– Hacker Rank Solution

Insertion Sort - Part 2 – Hacker Rank Solution


In Insertion Sort Part 1, you inserted one element into an array at its correct sorted position. Using the same approach repeatedly, can you sort an entire array?

Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an array with just the first element, it is already sorted since there’s nothing to compare it to.

In this challenge, print the array after each iteration of the insertion sort, i.e., whenever the next element has been inserted at its correct position. Since the array composed of just the first element is already sorted, begin printing after placing the second element.


Working from left to right, we get the following output:

3 4 7 5 6 2 1
3 4 7 5 6 2 1
3 4 5 7 6 2 1
3 4 5 6 7 2 1
2 3 4 5 6 7 1
1 2 3 4 5 6 7

Function Description

Complete the insertionSort2 function in the editor below.

insertionSort2 has the following parameter(s):

  • int n: the length of 
  • int arr[n]: an array of integers


At each iteration, print the array as space-separated integers on its own line.

Input Format

The first line contains an integer, , the size of .
The next line contains  space-separated integers .


Output Format

Print the entire array on a new line at every iteration.

Sample Input

STDIN           Function
-----           --------
6               n = 6
1 4 3 5 6 2     arr = [1, 4, 3, 5, 6, 2]

Sample Output

1 4 3 5 6 2 
1 3 4 5 6 2 
1 3 4 5 6 2 
1 3 4 5 6 2 
1 2 3 4 5 6 


Skip testing  against itself at position . It is sorted.
Test position  against position : , no more to check, no change.
Test position  against positions  and :

  • , new position may be . Keep checking.
  • , so insert  at position  and move others to the right.

Print arr
Test position  against positions  (as necessary): no change.
Print arr
Test position  against positions : no change.
Print arr
Test position  against positions , insert  at position  and move others to the right.
Print arr

Insertion Sort - Part 2 – Hacker Rank Solution
import java.util.Scanner;

 * @author Kanahaiya Gupta
public class InsertionSortPart2 {
	public static void insertionSortPart2(int[] ar) {
		for (int i = 1; i < ar.length; i++) {

			for (int j = i; j > 0; j--) {
				if (ar[j] < ar[j - 1]) {
					int temp = ar[j];
					ar[j] = ar[j - 1];
					ar[j - 1] = temp;
				} else {


	public static void main(String[] args) {
		Scanner in = new Scanner(;
		int s = in.nextInt();
		int[] ar = new int[s];
		for (int i = 0; i < s; i++) {
			ar[i] = in.nextInt();

	private static void printArray(int[] ar) {
		for (int n : ar) {
			System.out.print(n + " ");

1,191 thoughts on “Insertion Sort – Part 2 in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]”

  1. 22bet club oferuje ponad 450 gier najróżniejszego typu, w tym gry w 22bet kasyno polski z prawdziwymi krupierami oraz gry, w których do wygrania jest progresywny jackpot. Niniejsza platforma hazardowa 22Bet oprócz możliwości stawiania zakładów na wydarzenia sportowe, oferuje jeszcze kasyno online. To świetny pomysł na rozszerzenie działalności. Witryna istnieje od 2017 roku, więc nie jest to nowicjusz. O doświadczeniu możemy przekonać się przeglądając bardzo rozbudowaną ofertę tego bukmachera oraz niesamowicie profesjonalny interfejs strony internetowej. Czytaj dalej i poznaj więcej szczegółów. Punkty bonusowe zostaną przydzielone w dniu Twoich urodzin. Następnie, po przejściu do sklepu 22Bet, będziesz mógł wymienić je na darmowe zakłady bukmacherskie, spiny za free, premie pieniężne oraz gadżety od 22Bet.
    Wydawca:Media Rodzina Zabawna i ostra. Z ciekawymi historiami i mądrymi, opartymi na wiedzy, poradami. Praca z palantami to koło ratunkowe dla wszystkich, którzy mają do czynienia z trudnymi ludźmi. Czyli naprawdę dla prawie wszystkich! Wydawca:Gdańskie Wydawnictwo Psychologiczne GWP Autor:Goleman Daniel Zabawna i ostra. Z ciekawymi historiami i mądrymi, opartymi na wiedzy, poradami. Praca z palantami to koło ratunkowe dla wszystkich, którzy mają do czynienia z trudnymi ludźmi. Czyli naprawdę dla prawie wszystkich! Zabawna i ostra. Z ciekawymi historiami i mądrymi, opartymi na wiedzy, poradami. Praca z palantami to koło ratunkowe dla wszystkich, którzy mają do czynienia z trudnymi ludźmi. Czyli naprawdę dla prawie wszystkich!

  2. At Omni Slots, you can have lots of fun! Buckle up, the online casino has more than 1000 games to entertain you with. Create an account now and get a welcome package of up to C$500 + 70 Free Spins! Like any online casino, Omni Casino wants to entice new players into joining – and keep current customers playing – and one of how they do this is by offering a selection of welcome bonus offers and promotions. Below, we’re going to look at what bonuses you can expect to find at Omni Casino, both as a new player and an existing customer. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
    If you’ve spun in a win on one of our incredible online casino games, then you might have decided to withdraw your winnings. Any winnings from a deposit via your phone bill have no withdrawal cap. It’s important to note that if you have chosen to deposit with your phone bill, you’re effectively playing with credit. This means that we will need to see evidence that your phone bill has been paid off before any winnings that you may have, can be withdrawn. Definitely. In most cases, you will need to play at an Android or iPhone casino to find real money phone slots. Many phone slot apps are social games, meaning you do not win cash prizes. Most casinos will pay real money prizes to Sportsbooks. Mobile casinos are online casinos that you can access and play for real money on your mobile device. They will either be a mobile casino app or a web-based mobile app. You will have access to many of the same online casino games as you would at PC-based online casinos. Check out our casino reviews to see which licensed and legal casinos you can play at on mobile.

  3. Sebagai situs judi daftar slot terbaru serta terpercaya nomor 1 Sediakan daftar Situs Slot Gacor paling Baru Malam Ini untuk seluruh bettor judi slot online dengan Sediakan bermacam- macam berbagai permainan mengasyikkan semacam idn poker, slot online online, live casino online dengan bonus jackpot paling Besar. Tercantum di dalamnya beragam permainan popular semacam: sbobet, judi slot online, poker idn, 9Gaming Poker sudah disediakan buat penuhi kepuasan para member. Berbicara bergabung bersama DRAGON222 tentu semua member merasakan pengalaman terbaik menemukan game judi online dan slot online terbaru yang disukai. Kemudahan akses melalui berbagai perangkat situs judi slot online terpercaya penyedia bocoran slot gacor terpercaua dan terlengkap pembawa kegembiraan tanpa ragu khusus kepada setiap member yang sudah membuat ID bermain. Lantas apa sebenarnya yang istimewa dari situs slot online gacor no.1 di Indonesia? Mari kenali daftar keuntungan DRAGON222 melalui tabel berikut:
    150 Free Spins A lot of users want to claim free spins in addition to the welcome bonus, as this is an extremely profitable offer. Fans of slot games especially like it because it is such entertainment that users can use this promotion. Our experts have reviewed a huge number of sites with free spins no deposit win real money nz bonus, and we can highlight the best of them: This is a solid welcome bonus. Users who deposit at least NZ$10 will immediately get 50 free spins on Thor: The Trails of Asgard – with 30 more available to claim manually via the Kickers section. Each of the free spins is worth NZ$0.10. You won’t usually get many free spins no deposit on sign up, no wagering required NZ. These offers tend to be much smaller than no deposit free spin bonuses with wagering, so don’t expect to find 100 free spins that let you keep what you win. For a regular Kiwi player who likes free pokies, we think spins with wagering are the best option.

  4. Друг голям плюс на казината на живо онлайн е вашата сигурност. Вие може и да наблюдавате и общувате с дилърите на живо чрез livestreams, но вашата идентичност си остава тайна. Никой не може да види вас докато вие спокойно наблюдавате играта на живо. Уинбет пък от своя страна предлага уникален на пазара бонус – all inclusive, който важи за спорт, казино и казино на живо. Стойността на бонуса в онлайн казино уинбет не е висока – 100% до 200 лева, но поливалентността впечатлява повечето любители на залозите и казиното. Имате 14 дни, за да превъртите бонуса 30 пъти на казино игри.
    Това предложение е само за нови клиенти, регистрирани след 07.06.2021 г. Ефбет бонус без депозит в размер на 10лв. важи за регистрации, направени в промоционалния период 00:00ч. на 07.06.2021г. до 11.07.2021 включително. 300 ЛЕВАbetano » *Потребителите може да се регистрират и да депозират 10 лв или повече в тяхната сметка и да получат Кредити за Залози на стойността на техния квалифициращ депозит (до 100 лв), след като направят квалифициращи залози на същата стойност и те бъдат уредени. Само за нови клиенти, важат условия.

  5. cost of generic mobic no prescription [url=]can i order mobic[/url] can i purchase generic mobic for sale

  6. mexico pharmacies prescription drugs [url=]mexico drug stores pharmacies[/url] reputable mexican pharmacies online

  7. I’m not sure why but this blog is loading incredibly
    slow for me. Is anyone else having this issue or is it a issue on my end?
    I’ll check back later and see if the problem still

  8. To announce present rumour, adhere to these tips:

    Look in behalf of credible sources: It’s high-ranking to safeguard that the expos‚ origin you are reading is respected and unbiased. Some examples of reputable sources categorize BBC, Reuters, and The New York Times. Review multiple sources to get a well-rounded understanding of a precisely statement event. This can help you return a more ideal display and escape bias. Be aware of the viewpoint the article is coming from, as even reputable hearsay sources can compel ought to bias. Fact-check the gen with another fountain-head if a expos‚ article seems too unequalled or unbelievable. Always make unshakeable you are reading a known article, as tidings can substitute quickly.

    By means of following these tips, you can befit a more informed scandal reader and more intelligent know the world around you.

  9. To read present news, adhere to these tips:

    Look fitted credible sources: It’s eminent to guard that the newscast source you are reading is reliable and unbiased. Some examples of reliable sources subsume BBC, Reuters, and The New York Times. Interpret multiple sources to pick up a well-rounded aspect of a precisely low-down event. This can help you listen to a more ideal facsimile and keep bias. Be in the know of the position the article is coming from, as even respected hearsay sources can contain bias. Fact-check the low-down with another commencement if a expos‚ article seems too staggering or unbelievable. Many times make unshakeable you are reading a current article, as scandal can change quickly.

    Nearby following these tips, you can fit a more aware of dispatch reader and best know the beget everywhere you.

  10. Overview: Our best alternative UK live dealer welcome bonus is the package up to £50 by LeoVegas Casino. The 30% wagering contribution for live games is appealing, but your extra spins will be limited in Big Bass Splash. Still, you can use your live casino deposit bonus allows you to delve deeper into Evolution live casino games. Most online casinos offer what are called “No Deposit” Bonuses. That means you can play real money casino games without making any kind of deposit. By simply creating a new online casino account you instantly get bonus cash to test the waters. A 20x wagering requirement means you must playthrough your requirements 20 times before you can withdraw any winnings.Case: 100% up to £100 with a wagering requirement of x20.Bonus money example: Deposit £50 and get £50 bonus money. The wagering requirement is the bonus money multiplied by 20 (£50 x 20 = £1000).Deposit amount + Bonus money example: Deposit £50 and get £50 bonus money. The wagering requirement is the deposit amount + bonus money multiplied by 20 (£50 + £50 x 20 = £2000).
    The welcome doesn’t end there. Also included in the first of four welcomes is 200 free spins on top slot games Starburst and Fruit Zen. Wagering requirements are 49x winnings. The maximum bet is €10. The maximum possible win from the free spins without deposit is €50. The condition for receiving the bonus is the completion of the registration via account confirmation. Free games are valid for 24 hours. Check our help guide for more info. Importantly, there are no King Billy bonus codes for the first deposit. However, you’re required to provide a King Billy promo code for the rest. Other than that, all you need to qualify is deposit a minimum of $10. The wagering requirement is a competitive 35x and is valid for 30 days. The free spins are given at the rate of 20 per day for 10 days, and are available on Starburst or Fruit Zen. There is no extra King Billy promo code for the free spins.

  11. Absolutely! Declaration expos‚ portals in the UK can be awesome, but there are scads resources ready to boost you think the unmatched identical for you. As I mentioned before, conducting an online search with a view “UK news websites” or “British intelligence portals” is a pronounced starting point. Not but determination this give you a comprehensive shopping list of communication websites, but it determination also afford you with a improved understanding of the coeval hearsay view in the UK.
    Once you have a list of future story portals, it’s critical to gauge each one to influence which overwhelm suits your preferences. As an benchmark, BBC Dispatch is known in place of its intention reporting of report stories, while The Guardian is known pro its in-depth breakdown of political and sexual issues. The Independent is known representing its investigative journalism, while The Times is known in the interest of its affair and investment capital coverage. By entente these differences, you can choose the talk portal that caters to your interests and provides you with the hearsay you call for to read.
    Additionally, it’s significance looking at close by despatch portals for explicit regions within the UK. These portals produce coverage of events and scoop stories that are relevant to the area, which can be exceptionally cooperative if you’re looking to charge of up with events in your local community. In search occurrence, provincial news portals in London include the Evening Standard and the Londonist, while Manchester Evening Talk and Liverpool Reproduction are stylish in the North West.
    Inclusive, there are numberless tidings portals available in the UK, and it’s significant to do your inspection to remark the united that suits your needs. By evaluating the different news broadcast portals based on their coverage, luxury, and article perspective, you can choose the a person that provides you with the most apposite and attractive despatch stories. Esteemed luck with your search, and I anticipation this tidings helps you find the perfect news broadcast portal inasmuch as you!

  12. Altogether! Declaration information portals in the UK can be unendurable, but there are many resources ready to cure you espy the unexcelled identical as you. As I mentioned formerly, conducting an online search with a view “UK newsflash websites” or “British information portals” is a pronounced starting point. Not one purposefulness this give you a thorough shopping list of report websites, but it determination also provender you with a heartier savvy comprehension or of the current news scene in the UK.
    On one occasion you obtain a liber veritatis of future rumour portals, it’s powerful to estimate each one to shape which upper-class suits your preferences. As an exempli gratia, BBC News is known benefit of its disinterested reporting of news stories, while The Trustee is known quest of its in-depth analysis of partisan and social issues. The Independent is known pro its investigative journalism, while The Times is known by reason of its vocation and wealth coverage. By entente these differences, you can select the rumour portal that caters to your interests and provides you with the rumour you hope for to read.
    Additionally, it’s quality all things neighbourhood pub news portals representing proper to regions within the UK. These portals provide coverage of events and news stories that are relevant to the area, which can be especially accommodating if you’re looking to hang on to up with events in your close by community. For event, municipal communiqu‚ portals in London contain the Evening Pier and the Londonist, while Manchester Evening Scuttlebutt and Liverpool Reflection are stylish in the North West.
    Overall, there are many tidings portals available in the UK, and it’s high-level to do your experimentation to find the one that suits your needs. Sooner than evaluating the contrasting news programme portals based on their coverage, style, and position statement perspective, you can decide the a person that provides you with the most fitting and captivating despatch stories. Esteemed success rate with your search, and I anticipation this tidings helps you come up with the perfect dope portal since you!

  13. Anna Berezina is a famed author and demagogue in the area of psychology. With a family in clinical psychology and far-flung investigating circumstance, Anna has dedicated her employment to arrangement human behavior and unbalanced health: By virtue of her work, she has мейд important contributions to the strength and has behove a respected reflection leader.

    Anna’s expertise spans various areas of thinking, including cognitive of unsound mind, unquestionable certifiable, and passionate intelligence. Her voluminous facts in these domains allows her to victual valuable insights and strategies as individuals seeking offensive flowering and well-being.

    As an author, Anna has written some influential books that have garnered widespread notice and praise. Her books provide down-to-earth par‘nesis and evidence-based approaches to aide individuals lead fulfilling lives and evolve resilient mindsets. Via combining her clinical adroitness with her passion on serving others, Anna’s writings drink resonated with readers all the world.

  14. Anna Berezina is a highly proficient and renowned artist, known for her distinctive and captivating artworks that by no means fail to go away a lasting impression. Her work beautifully showcase mesmerizing landscapes and vibrant nature scenes, transporting viewers to enchanting worlds full of awe and marvel.

    What units [url=]Berezina A.[/url] apart is her distinctive consideration to element and her outstanding mastery of colour. Each stroke of her brush is deliberate and purposeful, creating depth and dimension that bring her paintings to life. Her meticulous approach to capturing the essence of her subjects allows her to create really breathtaking artistic endeavors.

    Anna finds inspiration in her travels and the magnificence of the pure world. She has a deep appreciation for the awe-inspiring landscapes she encounters, and this is evident in her work. Whether it’s a serene seaside at sunset, a majestic mountain range, or a peaceable forest full of vibrant foliage, Anna has a exceptional ability to seize the essence and spirit of these locations.

    With a singular creative type that mixes components of realism and impressionism, Anna’s work is a visual feast for the eyes. Her work are a harmonious blend of precise particulars and soft, dreamlike brushstrokes. This fusion creates a fascinating visual expertise that transports viewers into a world of tranquility and wonder.

    Anna’s talent and inventive imaginative and prescient have earned her recognition and acclaim within the artwork world. Her work has been exhibited in prestigious galleries around the globe, attracting the eye of art fanatics and collectors alike. Each of her items has a way of resonating with viewers on a deeply private level, evoking feelings and sparking a sense of reference to the pure world.

    As Anna continues to create gorgeous artworks, she leaves an indelible mark on the world of art. Her capacity to capture the beauty and essence of nature is really remarkable, and her work serve as a testament to her artistic prowess and unwavering ardour for her craft. Anna Berezina is an artist whose work will continue to captivate and inspire for years to return..

  15. zithromax for sale cheap [url=]buy Z-Pak online[/url] order zithromax without prescription

  16. buy zithromax canada [url=]buy azithromycin over the counter[/url] zithromax capsules price

  17. Coinbase is one of the most popular cryptocurrency apps and allows you to buy and sell Bitcoin, Ethereum, and other major altcoins. It’s one of the most user-friendly exchanges available, making it ideal for those new to cryptocurrency. In addition, it’s one of the most secure crypto apps. It offers the most secure and multifaceted risk management programs designed to protect its customers’ assets, boasting state-of-the-art encryption and security. Although the FCA does not regulate cryptocurrency exchanges in the UK, such as Crypto, the company is registered with the UK financial authoritative body. Our review found it complies with all financial and risk-prevention regulations but your funds may not be covered by the relevant compensation schemes.
    Conotoxia, Inc. is registered in the United States of America (NMLS #1504617). Office address: P.O Box 81320, Chicago, IL 60681, United States of America. This page covers everything you need to know about fees when buying cryptocurrencies through exchanges. Also, we’ll disclose the best crypto exchanges that have the lowest fees. A crypto exchange is a marketplace where you can buy and sell cryptocurrencies, like Bitcoin, Ether or Dogecoin. Cryptocurrency exchanges work a lot like other trading platforms that you may be familiar with. They provide you with accounts where you can create different order types to buy, sell and speculate in the crypto market. BitPanda is one of the largest cryptocurrency exchanges in Europe, offering both a brokerage and pro service. Whilst its brokerage features more convenience for higher fees, its pro service makes it one of the cheapest cryptocurrency exchanges available. The exchange is known for its safety measures, utilising DDOS protection and SSL encryption amongst other features.

  18. Howdy just wanted to give you a quick heads up and let you
    know a few of the images aren’t loading correctly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different web browsers and both show the same results.

  19. However, investors should be cognizant of Gemini’s fee structure, especially for smaller trades. For instance, a transaction ranging between $50 and $200 via the web interface incurs a $2.99 commission. But one can reduce fees by using Gemini’s ActiveTrader segment that offers more competitive fees. A cryptocurrency exchange is like an online brokerage for cryptocurrencies, tokens (virtual assets created through existing blockchains), and other digital assets. Many of these exchanges offer investment options for active traders looking to buy, sell, or hold digital assets like bitcoin, ether, and litecoin.  Trade BTC, ETH, and other crypto easily via bank transfer. Although Bitcoin has been around since 2009, cryptocurrencies and applications of blockchain technology are still emerging in financial terms, and more uses are expected in the future. Transactions including bonds, stocks, and other financial assets could eventually be traded using the technology.
    The three types of economic nodes (Strength, Thunder, and Mjolnir) receive rewards from the VeChain Foundation VTHO pool in addition to the normal reward for holding VET. – Exchange Crypto has the 2nd best withdrawal fee. VET withdrawal fees is ($0.0007779 – 0.05VET) this withdrawal fee on the chain network is VET . Deposit fee is Free. Minimum withdrawal amount VET is $0.0015558 and maximum is N A VeChain Price Part of the VIP-193, this mechanism will “balance the unpredictability and the unbiasedness” of the block production on the blockchain VeChainThor to increase its level of security. The foundation claimed: Demo Mode lets you try crypto trading with simulated funds. Experiment with your VeChain Trading Bot on various instruments and with different settings in a risk-free sandbox. The Demo Mode virtual account has all the same market conditions as real trading on the platform. Bitsgap will autonomously execute your orders, showing your actual trading results.

  20. where to get zithromax over the counter [url=]zithromax z-pak[/url] buy zithromax online with mastercard

  21. sildenafilo cinfa 25 mg precio [url=]comprar viagra en espana[/url] viagra online cerca de toledo

  22. farmacia online 24 horas [url=]Comprar Levitra Sin Receta En Espana[/url] farmacias baratas online envГ­o gratis

  23. Pharmacie en ligne fiable [url=]pharmacie en ligne pas cher[/url] Acheter mГ©dicaments sans ordonnance sur internet

  24. Pharmacie en ligne sans ordonnance [url=]kamagra pas cher[/url] acheter mГ©dicaments Г  l’Г©tranger

  25. acheter mГ©dicaments Г  l’Г©tranger [url=]Pharmacies en ligne certifiees[/url] п»їpharmacie en ligne