(In Java) 19.5 (Bubble Sort) Implement bubble sort—another simple yet inefficien
ID: 668489 • Letter: #
Question
(In Java)
19.5 (Bubble Sort) Implement bubble sort—another simple yet inefficient sorting technique. It’s
called bubble sort or sinking sort because smaller values gradually “bubble” their way to the top of
the array (i.e., toward the first element) like air bubbles rising in water, while the larger values sink
to the bottom (end) of the array. The technique 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 bubble sort leaves the values as they are. If a pair is in decreasing order, the
bubble sort 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.
Explanation / Answer
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int number, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
number = in.nextInt();
int array[] = new int[number];
System.out.println("Enter " + number + " integers");
for (c = 0; c < number; c++)
array[c] = in.nextInt();
for (c = 0; c < ( number - 1 ); c++) {
for (d = 0; d < number - c - 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
System.out.println("Sorted list of numbers");
for (c = 0; c < number; c++)
System.out.println(array[c]);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.