Exercise Beginner: Sort array(Bubble sort)

Request:
Write a program that inputs n natural numbers and a natural number k. Sort the input by non-descending order and then insert element k in such a way that the new resulted array is also sorted (1 ≤ n ≤ 1000, 1 ≤ numbers, k ≤ 1000000).

Solution
In order to be able to solve this exercise the programmer must know the concept of array which we have seen on lesson 8, if condition which we have seen on lesson 4 and the for loop which we have seen on lesson 7. So from the request we see that we must get from the user the k number. We can do this operation through the given code bellow:

Example code:

Where scannInt is an instance of Scanner class which is shipped within JDK and is found inside the java.util package, so in order to use it we need to add the line bellow in the beginning of the application if our class is not inside any package or directly bellow the package if the class is within a package.

Example code:

The request requires from us to get an array of integers from user as well, but the Scanner class does not have a method which allows us to get an array of integers from the user this is why we will use the nextLine method of Scanner class to get a line of string from the user, where we will have our numbers in a string separated from a space char which we will split than through split method of the String class as shown in the example code bellow.

Example code:

From the request we know that as result we want an array that has the size one more than the input array, this is why we will declare the result array with the size of input array + 1 as shown bellow.

Example code:

After we declare the resultArray we will give to it the value of the input array and in the last index we will put the k number as shown bellow.

Example code:

Now that we have all the elements on the resultArray we will sort the resultArray in order to get the requested result as shown bellow.

Example code:

So first we need a temporary variable which will store the value of a given index of the array in case that we will need to swap two elements of array. We will need to swap two elements of the resultArray if the previous element is greater than the next element of the array, this way we manage to put the greatest elements in the end of array every time that we execute the first for loop.

After we manage to sort the array we will need to display it through the following lines:

Example code:

Bellow is shown the complete code of the solution:

Example code:

In the figure 1 bellow can be seen an example of the execution of the application.


Figure 1: Execution


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game