Blog
Articles to grow your career
Article
1. Create a table for any array, in which to sequentially write the values of i, j
, array for each cycle of the bubble sort algorithm.
2. Use the debugger
.
3. For example, for the array 0 2 5 3 4
:
i | j | Array values | Is the “if” block executed? |
0 | 4 | 0 2 5 3 4 | – |
0 | 3 | 0 2 3 5 4 | + |
0 | 2 | 0 2 3 5 4 | – |
0 | 1 | 0 2 3 5 4 | – |
1 | 4 | 0 2 3 4 5 | + |
1 | 3 | 0 2 3 4 5 | – |
1 | 2 | 0 2 3 4 5 | – |
2 | 4 | 0 2 3 4 5 | – |
2 | 3 | 0 2 3 4 5 | – |
3 | 4 | 0 2 3 4 5 | – |
4 | – | 0 2 3 4 5 | – |
Change the bubble sort program:
a) add the possibility of early termination of sorting;
b) the program is written in such a way that the minimum element “floats” to the beginning of the array. Modify the program so that the minimum element “floats” to the end of the array (the inner for loop should iterate over the elements not from the end, but from the beginning).
Leave an application and get a free consultation from our manager.
public class BubbleSorter {
public static void sort(int[] array) {
for (int i = 0; i < array.length; i++) { for (int j = array.length - 1; j > i; j--) {
if (array[j - 1] > array[j]) {
int tmp = array[j - 1];
array[j - 1] = array[j];
array[j] = tmp;
}
}
}
}
}
Change selection sort – exclude value exchange if the found minimum element is already in its place.
public class SelectionSorter {
public static void sort(int[] array) {
for (int i = 0; i < array.length; i++) { // i - id of the current iteration
int pos = i;
int min = array[i];
// loop for the selection of the smallest element
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
pos = j; // pos - index of the smallest element
min = array[j];
}
}
array[pos] = array[i];
array[i] = min; // swap places min with array[i]
}
}
}