Tuesday, 25 August 2015

Java Practice 7

Write a program for bubble sort?

  1. import java.util.Scanner;
  2.  
  3. class BubbleSort {
  4. public static void main(String []args) {
  5. int n, c, d, swap;
  6. Scanner in = new Scanner(System.in);
  7.  
  8. System.out.println("Input number of integers to sort");
  9. n = in.nextInt();
  10.  
  11. int array[] = new int[n];
  12.  
  13. System.out.println("Enter " + n + " integers");
  14.  
  15. for (c = 0; c < n; c++)
  16. array[c] = in.nextInt();
  17.  
  18. for (c = 0; c < ( n - 1 ); c++) {
  19. for (d = 0; d < n - c - 1; d++) {
  20. if (array[d] > array[d+1]) /* For descending order use < */
  21. {
  22. swap = array[d];
  23. array[d] = array[d+1];
  24. array[d+1] = swap;
  25. }
  26. }
  27. }
  28.  
  29. System.out.println("Sorted list of numbers");
  30.  
  31. for (c = 0; c < n; c++)
  32. System.out.println(array[c]);
  33. }
  34. }