Pages

Thursday, 25 August 2016

Chapter 7 Exercise 18, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**7.18 (Bubble sort) Write a sort method that uses the bubble-sort algorithm. The bubblesort algorithm makes several passes through the array. On each pass, successive neighboring pairs are compared. If a pair is not in order, its values are swapped; otherwise, the values remain unchanged. The technique is called a bubble sort or sinking sort because the smaller values gradually “bubble” their way to the top and the larger values “sink” to the bottom. Write a test program that reads in ten double numbers, invokes the method, and displays the sorted numbers.



import java.util.Scanner;
 
 
public class ProgrammingEx7_18 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  double[] numbers = new double[10];
 
  System.out.print("Enter ten numbers:");
 
  for (int i = 0; i < numbers.length; i++) {
   numbers[i] = input.nextDouble();
  }
  bubleSort(numbers);
   
  System.out.println("The array after sort is:");
  for (int i = 0; i < numbers.length; i++) {
   System.out.println(numbers[i]);
  }
   
 }
 
 public static void bubleSort(double[] list) {
 
  int n = list.length - 1;
  while (n != 0) {
   int i;
   for ( i = 0; i < n; i++) {
    if (list[i] > list[i + 1]) {
     double temp = list[i];
     list[i] = list[i + 1];
     list[i + 1] = temp;
    }
     
   }
   n= i-1;
  }
 
 }
}

No comments:

Post a Comment