Archive for the ‘Java’ Category:

What Is An Insertion Sort Algorithm – Its Basic Definition

If you need to get a good understanding of what an insertion sort algorithm is, the best way to start is with a basic definition of what an algorithm is.

An algorithm in its purest sense is just a formula or method for solving a problem. Even a simple task may include an algorithm by utilizing a standard process for arriving at a solution. This could include a variety of types of problems, and their associated resolutions:

  • Manual tasks such as how to select the best grocery products
  • Solutions to mathematic problems
  • Computer system processes that solve business problems

Modern computer applications are where insertion sort algorithms enter the picture. In computer science and mathematics, an algorithm is a defined specification that eases the burden of solving even complex problems.

By formalizing a process or function as a proven algorithm, programmers and scientists can reuse code and formulas to solve business and mathematical problems more efficiently.

Computer algorithms are essentially program logic that receives input values and produces consistent, reliable results as output. Algorithms can be applied for automated and consistent reasoning, performing calculations, and yes – sorting.

Types of Sorting


There are multiple methodologies and algorithms for conducting computer sorting:

Select Columns Layout
  • Insertion sort
  • Bucket sort
  • Bubble sort
  • Selection sort
  • QuickSort
  • Counting sort
  • Merge sort
  • Radix sort
  • and others

Even within those variations in processing, and the applicable uses for each, there are additional classifications such as recursive insertion sort, binary insertion sort, recursive merge sort, and so on.

Insertion Sort Explained

So just what is an insertion sort algorithm?

Insertion sort algorithms work much in the same way as you would in sorting a deck of cards. Assume someone gives you stack of playing cards, already in order (or even a single card). Then they give you another card, asking you to place it in the proper sequence in the deck. You will scan through the deck you have, then insert the new card in its place.

Next, you’re given another card, with the same request – put in the deck – in sequence. With many iterations of cards passed to you, the process is repeated. This is essentially the process in working with an insertion sort algorithm.

For each iteration, processing is required to shift the array to insert the new entry, which can be an important factor in utilizing an insertion sort when large arrays or data sets are anticipated. In effect, the insertion sort algorithm proceeds in this manner:

  • Select the first element (since it is the first one, it is already in place, and no shifting is necessary)
  • Pick the next entry from the input array
  • Compare the value against the sorted list
  • Shift all elements higher than the new entry to the right
  • Insert the new entry
  • Repeat the process until the entire input set is complete, resulting in a sorted output set

This provides a reasonably straight-forward process, yet also reveals how the algorithm can result in considerable processing, when the input set is composed of extremely large arrays.

Variations of an Insertion Sort


Within the realm of insertion sort processing, there are additional variations:

Binary insertion sort - binary insertion sort can be used to reduce the actual number of comparisons over a normal insertion sort. By utilizing a binary search function to insert an element in the proper position of the output set, less processing is required. Normal insertion sort will require multiple iterations for comparison, depending on the size of the input array. In a worst case of large arrays, the binary insertion sort can have significant performance advantages.

Recursive insertion sort–insertion sort algorithms can also be written recursively, although this could have a negative impact on performance. Recursion can simplify coding of the algorithm, but can increase processing requirements.

Insertion sort methodology is more commonly implemented in a non-recursive manner.

Insertion Sort Algorithm Characteristics/Caveats

One factor of sorting algorithms is the attribute of being termed stable or unstable. This refers to the occurrence of equal values in array elements, and whether the sequence of those elements will be retained in the same order as originally encountered in the output set. Insertion sort algorithms are stable by their very nature.

Divide and conquer – algorithms that implement a divide and conquer methodology process data elements utilizing a somewhat more complex approach:

  • Divide – separate the data to be processed into multiple smaller sets of data
  • Conquer – recursively process the subsets of data to execute the algorithm separately
  • Combine – generate the resulting output set through combining the subsets

As divide and conquer algorithms require multiple steps, they are recursive in their processing methodology. Where large sets of data are involved, this type of algorithm can provide an advantage in run times (time complexity).

Insertion sort is not a divide and conquer algorithm, processing elements in a single pass.

Why Would You Use (or Not Use) an Insertion Sort Algorithm?

With the many variations of sort algorithms, why would you decide you use the insertion sort algorithm for any particular problem?

When to Use Insertion Sort

Utilizing an insertion sort algorithm can be an effective solution under certain conditions:

  • Input sets are relatively limited in size
  • Input sets are partially sorted, which increases the efficiency of the algorithm, through the requirement for fewer iterations
  • Space is a consideration – insertion sort requires only a single new memory space, reducing space complexity
  • Stability is an important factor – insertion sort is a stable algorithm, making it an effective choice when that is important for your output set
  • For managing online content, where your application receives one element at a time, insertion sort is a great choice due to its performance in handling such small volumes

Benefits of the insertion sort algorithm include its low overhead and simplicity. When a pre-sorted or partially-sorted input set is expected or known, performance of the insertion sort algorithm can be significantly better than many alternatives, including divide and conquer algorithms such as merge sort, heap sort, even QuickSort.

When Not to Use an Insertion Sort Algorithm


In many instances, the size of the input set to your sort algorithm is unpredictable, or you may even be aware that the volume of data will be large. In such use cases, insertion sort will not be a good choice to solve your sort requirements.

With average and worst-case scenarios (refer to Big O Notation later in this article), alternatives such as merge sort and heap sort will provide better performance.

Insertion sort is not your best choice when concerned with:

  • Large data volumes – insertion sort performance suffers with large input sets
  • Space is not an issue – divide and conquer algorithms will have a higher space complexity, but if that is not an issue, there are better options than insertion sort
  • Stability is not required – for many implementations, stability in the output is not a requirement, allowing the use of non-stable algorithmsthat offer better performance
  • If the input array is unsorted or reverse-sorted, insertion sort will not result in good performance
  • Optimizing processor use – larger data volumes will result in more CPU cycles when implementing an insertion sort algorithm over a divide and conquer solution

Making the Best Choice for Your Sorting Algorithms

Mathematicians and computer scientists have developed a set of guidelines termed Big O Notation, which provides guidelines for the efficiency of different sorting algorithms based on critical factors:

  • Efficiency in run times (time complexity)
  • Space requirements (space complexity)

Binary insertion sort

These algorithm variations have even been compiled into a “cheat sheet” that provides a quick reference to these factors, including performance in best, average, and worst case scenarios.For an insertion sort algorithm, worst case conditions occur when the input set is in reverse order, with best case being where the input set is already sorted.

Additional information, including tutorials on Big O Notation can be found on YouTube and on multiple websites.

It pays to do a little research before making your final choice of sort algorithm solutions. There are divide and conquer algorithms that determine the size of the input set first, and automatically switch to another alternative such as selection sort or insertion sort to process small arrays more efficiently.

Sorting algorithms that are right for your application will depend on the volume of data to be sorted, the condition of the data itself (duplicate values, pre-sorting, etc.), space requirements, and even the programming language in use (not all sorting techniques are supported by every language).

What Is A Merge Sort Algorithm And How It Is Used

A primary function of every computer system is to organize data for effective use in analysis, reporting, or presentation purposes. You certainly cannot expect to logically make sense of data that is presented in a random sequence, and make judgements or decisions based on the information.

To solve that problem, computer programmers and mathematicians have created a variety of sorting algorithms that transform non-sequenced data into elements that are sorted into sets of records that provide information in a meaningful manner for business or scientific use.

In today’s sophisticated computer systems that commonly utilize extremely high data volumes for intelligent analysis – referred to as “big data”, efficient sorting techniques are more critical than ever before.

A merge sort algorithm is one of the more commonly-used and powerful solutions for sorting data structures and data content quickly and efficiently.

Sorting Efficiently with a Merge Sort Algorithm

colorful drinks

There are many options available to computer application developers for sorting sets of data to generate organized output.

Selection of the algorithm to be utilized is to some extent dependent on the language being utilized (ex: C++ “sort()” function can select a different algorithm depending on the array presented for sorting. Its native algorithm is the Introsort function, a blend of heapsort, insertion sort, and quicksort methodology. Depending on the depth of recursion of the array, quicksort or heap sort may be performed. For extremely small arrays, the high performance of insertion sort algorithm will be selected.

When executing a sort function in Python, a combination of insertion sort and merge sort will be used, known as Timsort.

A merge sort algorithm will sort an array into the desired sequence quickly and efficiently, utilizing a divide and conquer methodology. As with many sort algorithms, with a merge sort algorithm the array test will detect the size of the array, and if the size is 0 or 1, consider the data sorted with no processing required.

What is a Divide and Conquer Algorithm?

But what is a merge sort algorithm, and what makes it different from other sorting techniques?

Merge sort is just one of several divide and conquer algorithms that accomplishes its functions in a multi-step process:

  • Divide the array intotwo equal smaller arrays for processing efficiently

This is a simple process of dividing the array size by 2 to determine the midpoint, and creating the two subsets

  • Solve the sequencing of each subarray individually – conquer the problem

This is also a straight-forward process involving recursive calls for each subarray to execute the sort process

  • Combine the sorted subarrays back into the complete original array, now in sequence – this is the merge function that gives the algorithm its name, and requires heavy comparison processing to create the final result set

This divide, conquer, combine process can be performed much more efficiently than other methods such as insertion sort algorithm, which can take a considerable amount of processing time when arrays exceed more than minimal depth.

Array depth is one of the most important elements in determining the sort algorithm that will perform most efficiently when implemented in your solution. Other considerations include space requirements, memory available, and overall performance.

Since a merge sort algorithm will generate additional arrays in memory while processing the input set (divide), space is an important consideration in using merge sort for large arrays. Your trade-off is in performance – time complexity is a major advantage in using a divide and conquer algorithm like merge sort. Since these algorithms create subarrays as part of their basic functions, they are recursive in execution.

Factors for consideration in sort algorithm selection are available on websites for your comparison and decision-making purposes.

Merge Sort Variations


There are multiple variations or implementations of merge sort algorithms, providing options and flexibility in your choice of sorting methodology:

3-way merge sort

In a 3-way merge sort, instead of sub-setting the input array into two subarrays, three equally-sized separate arrays are created, sorted, then merged. Although the time complexity would seem to be reduced due to the smaller arrays being sorted, the increased number of comparisons required in the merge operation will raise the time complexity during that phase.

Bottom-up Implementation

Bottom-up processing utilizes indices and two buffers to iteratively merge sub-lists between the buffers to sort elements into the sorted array. The result is a non-recursive merge sort, contrary to the typical recursive nature of other merge sort variations.

Polyphase Merge Sort

This variation of a bottom-up merge sort is geared for external data sources where multiple files are being sorted, often including data stored on a hard drive or even a tape device. This includes data sets that will be uneven or unknown in their array sizes, being external input to the algorithm. Due to that criteria, polyphase merge sorts are not stable in nature.

Natural Merge

Similar to the processing of a bottom-up merge, natural merge further examines any existing sorted elements (naturally-occurring sequenced data), and takes advantage to move these elements in a single pass to the result set. In a perfect case, the array will be found to be in sequence, resulting in a single pass to create the solution. Even in a partially-sequenced array, the impact can be improved performance though fewer passes to solve the problem.

Oscillating Merge

Do you ever deal with data from tape drives, especially those that can read backwards? Oscillating merge sort algorithm was designed with that technology in mind. This variation of merge sort intersperses the input data with the merge process, rather than reading the entire set of data before merging can begin.

Pros and Cons of a Merge Sort Algorithm

Not all sort algorithms are created equal – in fact, there are significant differences that will impact your decision on the best sort algorithm for solving your problem.


  • Merge sort utilizes additional space over the original array to create its subsets of data to solve the problem and create sorted output.
  • A merge sort algorithm will process large arrays with reduced time complexity over many other options, notably an insertion sort algorithm.
  • Where stability is an important factor for your application, merge sort is a viable choice, since it is a stable algorithm. Stability means that where values being sorted are equal in multiple elements, the resulting output will retain the original sequence of those elements.


  • Space restrictions –since additional space is required to create the subsets of data for divide and conquer algorithms, you need to have space available to utilize this sort method.
  • Small arrays – where very small arrays will be sorted, other non-recursive, single-pass algorithms such as insertion sort may be more efficient.

Since the merge step makes an additional copy of the array to accomplish its work, extra space is required. While some algorithms such as insertion sort and selection sort do their work “in place” and are therefore preferred where space is at a premium, merge sort is not an in-place algorithm.

There is an exception to the requirement for a merge sort algorithm’s need for additional space to process – use of a linked list. Due to the nature of how linked lists reside in memory, no additional space is required for a merge sort with linked lists.

Factors for Choosing the Best Sort Algorithm


Now that you’re comfortable with the concept of what a merge sort algorithm is, your dilemma may be what sort algorithm to utilize in your application. Big O Notation is a representation of how algorithms will perform, based on primary factors:

  • Time Complexity
  • Space Complexity
  • Array Size

Considering those factors plus any special requirements you have in your problem (such as stability issues mentioned earlier), you can make the decision on the algorithm that will perform best for your data and meet your application performance goals.

Where space is not a major consideration, there are additional sort algorithms to be explored for potentially improving your application performance and efficiency:

  • QuickSort
  • Heap Sort
  • Bucket Sort
  • Bubble Sort

There are additional sort algorithms available for your applications, each with their own pros and cons. Some are more useful when used with certain programming languages or may be more useful for website applications (such as insertion sort algorithms).

Utilizing sort selection tools and Big O Notation guidelines can help you determine the best sort algorithm for your implementation.

Keywords:What is a merge sort algorithm, merge sort

Java Interview Questions

The Top 21 Most Common Java Interview Questions

It pays to know of the one most popular programming languages.

In 2016, Oracle noted Java was used by approximately 9 million developers and running on 7 billion devices worldwide. That’s an exponential growth curve, considering it’s only been public for less than 25 years.

Java was born in Santa Clara, California as part of the Silicon Valley boom in the early 1990s. Java was developed at Sun Microsystems to boost the abilities and effectiveness of C++ language.

It was released to the public in 1995 and quickly gained popularity. Java was designed to run independent of platform. Any device that has Java Runtime Environment (JRE), a lightweight application, can run a Java program. This provided developers a “write once, run anywhere” programming language. It significantly reduced the coding and resources necessary to write a program for multiple platforms.

Java was eventually acquired by Oracle as part of its larger purchase of Sun in January 2010.

Of all the programming languages available, how did Java surpass them and become such a hot commodity in today’s job market?

Why Java is One of the Top Programming Languages

Java is undeniably popular. It consistently leads the TIOBE index – a measure of the popularity of programming languages created by the TIOBE Company in the Netherlands – with the most recent rating of 17.8%. That’s up 5.4% from last year.

Below are just a few of the reasons why Java has become so popular:

  • The Five Principles: Sun Microsystems wanted to build on the C++ language and create something that more people could use. They explained this goal as Five Principles which guided the initial design and subsequent iterations of the language.
  • Open Source: Anyone can create Java applications at no cost. A massive community of users has grown around Java, providing additional resources and expertise for developers. Message boards and forums provide free publicity and ongoing training for users. With a growing library of functions and classes, Java is an easy choice when looking to deliver results quickly.
  • Concurrent: Programmers can process data in parallel, meaning multiple programs can run at the same time. This increases the efficiency and power of programs written in Java.
  • Wide Range of Uses: Java is used in banking and financial services, IT, and stock market trades. It provides a solid foundation for websites. Java is critical for applications in a wide range of industries.
  • Big-Name Users: Companies and programs that use Java include Minecraft, Adobe Creative, Google, and more.

Thanks to the high demand for this skill set, average salary range has been reported at $93,570 for a Java programmer. It’s no wonder Java developers and programmers are in such demand.

Knowing Java is only part of what you need to earn a position with one of the top companies in the world. Let’s look closely at the interview process and the questions you can expect.

Interview Questions

The interview is designed to give the business a better understanding of who you will be as an employee and how you will work as part of a team. The questions will also cover specific technical skills you’ll need.

Problem-Solving Questions

Managers want problem solvers in every layer of employment – from entry level to top management. The hiring manager will test your personal skills by asking about missed deadlines, office conflicts, loss of data, and overlapping deadlines. They are not only looking to see that you know how to fix a problem but want to know how you can deliver solutions when problems occur. Below are a few of the questions you should prepare to answer:

  • What is a challenge you’ve faced in the past and how did you handle it?
  • Have you ever had a project that was behind schedule? How did you manage the work and meet the deadline?
  • Tell me about a time where you faced a problem you couldn’t solve. How did you handle it?
  • Describe a creative solution you used to handle a work-related problem?
  • What kind of troubleshooting process do you use in your work?

Leadership-Based Questions

Do you wait for a solution or do you lead by proactively finding the answer? Everyone has their comfort zone with leadership. Hiring managers want to know where you will fit within the company. They may ask questions about your proudest accomplishment, what do you want to gain from this job, or if would you speak up if you knew something in the process was wrong.

  • In your opinion, what makes a great leader?
  • What experience do you have that will help you in this position?
  • What work-related responsibilities have you had in the past?
  • If you knew a manager was wrong, how would you handle it?
  • What is your greatest strength and greatest weakness?

Java Interview Questions

Java is considered one of the easier programming languages, especially when compared to languages like C, C++, Fortran, and Pascal. Even so, there are core skills and expertise every developer and programmer working in Java should have mastered.

The technical questions in the interview will be designed to not only determine your comfort and competence in Java programming, but also check that you have the core skills for the position. Before the interview, make sure to review the job listing to identify what those skills are. Take time to brush up on those skills and have answers ready for any specific technical questions the interviewer might ask.

Let’s look at a few other common Java interview questions:

  • Can you explain what a “platform independent programming language” means, and why Java fits this description?
  • Can you explain the difference between StringBuffer and String?
  • Tell me what you know about the finalize() method?
  • Can you explain the difference in Set and List interface?
  • Why doesn’t Java support multiple inheritances?
  • Tell me what you know about Java Exception Handling? Is there a difference between “throw” and “throws”?
  • What is the Final keyword in Java? How is a super keyword used?
  • Can you explain the abstract class in Java? How is it different from an abstract class in C++?
  • How does static variable work in Java?
  • How does Java store objects in memory?
  • What are the differences between HashTable and HashMap in Java?

Keep in mind, these are common Java interview questions. Many jobs will require specialized technical knowledge and Java programming that isn’t covered by these questions. Understand the position you are interviewing for and the expectations for the job.

Next, we’ll go over a few other things you can do to ace your interview.

Appearances Mean Everything

Beyond knowing the answers to the top interview questions, landing the job is all about first impressions and professionalism. Employers are looking for Java programmers that fit within the corporate culture and take pride in themselves. Confidence in your abilities translates to confidence in your appearance and mannerisms.

Below are some guidelines to acing the first impression:

Prepare for the Interview

You are an expert in your field, Java programming, but companies also expect you to know about them and how they are using Java. Go beyond the simple Google search and see what the company says about itself. Look at what others are saying about the company and who are their competitors. Review their business pain points and prepare responses on how you can solve them.

Dress Appropriately

Sometimes a recruiter or the hiring manager will provide guidelines on what to wear. If they don’t, do your research and learn what is expected in the corporate culture. Not every company will expect a suit, but some won’t give you a second glance if you wear jeans. In general, interviews tend to be more formal than your daily wear once you land the job.

  • Here are recommendations for women, including what to wear and suggestions on where to buy layers, blazers, dresses, and pants. You don’t have to buy the exact item in the article; use it as a guideline and tailor it to your style and budget.
  • Likewise, there are also suggestions for men for ties, shirts, and trousers. Again, make the style your own, but make sure it fits the expectations.

Print your Resume

Some companies and human resource departments still prefer paper. Print and bring a copy of your resume. It’s better to have it and not need it, then to not be prepared for someone to review your resume.


Store your printed resume, laptop and any samples in a portfolio or briefcase, so they are crisp when you arrive. You will lose credibility if your work looks sloppy.

Follow Up

Gather business cards or contact information during the interview. Email a thank-you note within 24 hours (the sooner the better) of the interview. Express not only your thanks, but also your excitement and recap what you can bring to the company.

A Final Word on Java Interview Questions 

Learning Java is only the first step in a career. Even as the demand for quality employees and the sheer number of companies using Java continues to rise, competition for jobs is still fierce.

Preparing for Java interview questions and doing your research before you meet with a recruiter is critical to landing the job you want. You may be the best Java programmer for a position, but if you can’t ace the interview and show what an asset you will be for the company, you may never get a chance to show what you can do.

Meta Information

Focus Keyword(s): Java Interview Questions

Meta Keywords: Java programming, Java programmer

Meta Title: The Top 21 Most Common Java Interview Questions

Meta Description: Competition is fierce for Java programmer jobs. Stay ahead of the competition with these top Java interview questions.

WordPress Tags: Java, Java interview questions, Java programming

How System.out.println() works

In Java, how does System.out.println() work?

This question is an excellent example of how just some very basic knowledge of Java can lead you to the correct answer. Most interviewers would not expect you to know the answer to do this right away – but would like to see how you think and arrive at an answer.

Marcus Aurelius (a Roman emperor) once said: "Of each particular thing ask: what is it in itself? What is its nature?". This problem is an excellent example of how that sort of thinking can help one arrive at an answer with only some basic Java knowledge.

With that in mind, let’s break this down, starting with the dot operator. In Java, the dot operator can only be used to call methods and variables so we know that ‘out’ must be either a method or a variable. Now, how do we categorize ‘out’? Well, ‘out’ could not possibly be a method because of the fact that there are no parentheses – the ‘( )’ – after ‘out’, which means that out is clearly not a method that is being invoked. And, ‘out’ does not accept any arguments because only methods accept arguments – you will never see something like “System.out(2,3).println”. This means ‘out’ must be a variable.

What is “out” in System.out.println()?

We now know that ‘out’ is a variable, so we must now ask ourselves what kind of variable is it? There are two possibilities – it could be a static or an instance variable. Because ‘out’ is being called with the ‘System’ class name itself, and not an instance of a class (an object), then we know that ‘out’ must be a static variable, since only static variables can be called with just the class name itself. So now we know that ‘out’ is a static member variable belonging to the System class.

Is “out” in System.out.println() an instance variable?

Noticing the fact that ‘println()’ is clearly a method, we can further classify the ‘out’ in System.out.println(). We have already reasoned that ‘out’ is a static variable belonging to the class System. But now we can see that ‘out’ must be an instance of a class, because it is invoking the method ‘println()’.

The thought process that one should use to arrive at an answer is purposely illustrated above. Without knowing the exact answer beforehand, you can arrive at an approximate one by applying some basic knowledge of Java. Most interviewers wouldn’t expect you to know how System.out.println() works off the top of your head, but would rather see you use your basic Java knowledge to arrive at an answer that’s close to exact.

When and where is the “out” instantiated in System.out.println?

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().

The final answer to how system.out.println() works

The more exact answer to the original question is this: inside the System class is the declaration of ‘out’ that looks like: ‘public static final PrintStream out’, and inside the Prinstream class is a declaration of ‘println()’ that has a method signature that looks like: ‘public void println()’.

Here is what the different pieces of System.out.println() actually look like:

//the System class belongs to java.lang package
class System {
  public static final PrintStream out;

//the Prinstream class belongs to package
class PrintStream{
public void println();