In: Computer Science
. Consider the following sorting procedure. This procedure uses nested loops to make several passes through the array. Each pass compares successive pairs of elements. If a pair is in increasing order (or the values are equal), the sorting procedure leaves the values as they are. If a pair is in decreasing order, the sorting procedure swaps their values in the array. The first pass compares the first two elements of the array and swaps their values if necessary. It then compares the second and third elements in the array. The end of this pass compares the last two elements in the array and swaps them if necessary. After one pass, the largest element will be in the last index. After two passes, the largest two elements will be in the last two indices. After n – 1 pases (where n is the size of the array), the largest n – 1 elements will be in the last n – 1 indices and we have a sorted array.(java
thanks for the question, the steps given in the question are the algorithm steps of a bubble sort. Below is the code in Java that contains the sort() method, the sort() method takes in an int array and sorts the numbers based on the steps given in the question.
In order to demonstrate, at the end of every pass i have printed the array in order to visualize how the largest numbers are getting shifted to the end.
Here is the code and screenshot. You can remove or comment the print statements if needed
===========================================================================
import java.util.Arrays;
public class Main {
public static void
sort(int[] array) {
for
(int pass = 0; pass <
array.length; pass++) {
for (int j = 0; j <
array.length - 1 - pass; j++) {
if (array[j] > array[j + 1]) {
int swap = array[j];
array[j] = array[j + 1];
array[j + 1] = swap;
}
}
System.out.println("Pass -
" + (pass + 1));
System.out.println(Arrays.toString(array));
}
}
public static void
main(String[] args) {
int
num[] = {5, 6, 1, 2, 8, 9, 3, 4, 7, 0};
sort(num);
}
}
===========================================================================