# Java Sorting Algorithm: Exercises, Practice, Solution

## Java Sorting Exercises [19 exercises with solution]

[*An editor is available at the bottom of the page to write and execute the scripts.*]

**1.** Write a Java program to sort an array of given integers using Quick sort Algorithm. Go to the editor

Quick sort is a comparison sort, meaning that it can sort items of any type for which a "less-than" relation (formally, a total order) is defined.

Click me to see the solution

**2.** Write a Java program to sort an array of given integers using the Bubble sorting Algorithm. Go to the editor

According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position."

Click me to see the solution

**3.** Write a Java program to sort an array of given integers using Radix sort Algorithm. Go to the editor

According to Wikipedia "In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value".

Click me to see the solution

**4.** Write a Java program to sort an array of given integers using Merge sort Algorithm. Go to the editor

According to Wikipedia "Merge sort (also commonly spelled mergesort) is an O (n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output."

Click me to see the solution

**5.** Write a Java program to sort an array of given integers using Heap sort Algorithm. Go to the editor

In computer science, heapsort (invented by J. W. J. Williams in 1964) is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it interactively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.

Click me to see the solution

**6.** Write a Java program to sort an array of given integers using Selection Sort Algorithm. Go to the editor

According to Wikipedia "In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort".

Click me to see the solution

**7.** Write a Java program to sort an array of given integers using Insertion sort Algorithm. Go to the editor

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than other algorithms such as quicksort, heapsort, or merge sort.

Click me to see the solution

**8.** Write a Java program to sort an array of positive integers using the Bead Sort Algorithm. Go to the editor

According to Wikipedia "Bead sort, also called gravity sort, is a natural sorting algorithm, developed by Joshua J. Arulanandham, Cristian S. Calude and Michael J. Dinneen in 2002, and published in The Bulletin of the European Association for Theoretical Computer Science. Both digital and analog hardware implementations of bead sort can achieve a sorting time of O(n); however, the implementation of this algorithm tends to be significantly slower in software and can only be used to sort lists of positive integers. Also, it would seem that even in the best case, the algorithm requires O(n2) space".

Click me to see the solution

**9.** Write a Java program to sort an array of positive integers using the BogoSort Sort Algorithm. Go to the editor

In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting but may be used for educational purposes, to contrast it with other more realistic algorithms.

Click me to see the solution

**10.** Write a Java program to sort an array of positive integers using the Cocktail sort Algorithm. Go to the editor

Cocktail shaker sort (also known as bidirectional bubble sort, cocktail sort, shaker sort, ripple sort, shuffle sort, or shuttle sort ) is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than a bubble sort and solves the problem of turtles in bubble sorts. It provides only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort, it is not of practical interest, though it finds some use in education.

Click me to see the solution

**11.** Write a Java program to sort an array of given integers using the CombSort Algorithm. Go to the editor

The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Some implementations use the insertion sort once the gap is less than a certain amount. The basic idea is to eliminate turtles, or small values near the end of the list, since in a bubble sort these slow the sorting down tremendously. Rabbits, large values around the beginning of the list do not pose a problem in bubble sort.

Click me to see the solution

**12.** Write a Java program to sort an array of given integers using CountingSort Algorithm. Go to the editor

According to Wikipedia "In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently".

Click me to see the solution

**13.** Write a Java program to sort an array of given integers using Gnome sort Algorithm. Go to the editor

Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort" (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort".

The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.

Click me to see the solution

**14.** Write a Java program to sort an array of given integers using Pancake sort Algorithm. Go to the editor

Pancake sorting is the colloquial term for the mathematical problem of sorting a disordered stack of pancakes in order of size when a spatula can be inserted at any point in the stack and used to flip all pancakes above it. A pancake number is the minimum number of flips required for a given number of pancakes. The problem was first discussed by American geometer Jacob E. Goodman. It is a variation of the sorting problem in which the only allowed operation is to reverse the elements of some prefix of the sequence.

Click me to see the solution

**15.** Write a Java program to sort an array of given integers using Permutation sort Algorithm. Go to the editor

Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.

Click me to see the solution

**16.** Write a Java program to sort an array of given integers Shell Sort Algorithm. Go to the editor

According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange."

Click me to see the solution

**17.** Write a Java program to sort an array of given non-negative integers using Sleep Sort Algorithm. Go to the editor

Sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.

Click me to see the solution

**18.** Write a Java program to sort an array of given non-negative integers using Stooge Sort Algorithm. Go to the editor

Stooge sort is a recursive sorting algorithm with a time complexity of O(*n*log 3 / log 1.5 ) = O(*n*2.7095...). The running time of the algorithm is thus slower compared to efficient sorting algorithms, such as Merge sort, and is even slower than Bubble sort.

Click me to see the solution

**19.** Write a Java program to sort an array of given integers using Bucket Sort Algorithm. Go to the editor

Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, a generalization of pigeonhole sort, and is a cousin of radix sort in the most-to-least significant digit flavor.

Click me to see the solution

**Java Code Editor:**

**More to Come !**

**Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.**

## Java: Tips of the Day

** Check if at least two out of three booleans are true**:

Rather than writing:

if (someExpression) { return true; } else { return false; }

Write:

return someExpression;

As for the expression itself, something like this:

boolean atLeastTwo(boolean a, boolean b, boolean c) { return a ? (b || c) : (b && c); }

or this (whichever you find easier to grasp):

boolean atLeastTwo(boolean a, boolean b, boolean c) { return a && (b || c) || (b && c); }

Ref: https://bit.ly/2OYPQD7

**New Content published on w3resource:**- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework