Advertisement
Chame

Untitled

Dec 20th, 2011
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. /*Author: Andrew Closs
  2. * Version: 1.0
  3. * Date: December 18th, 2011.
  4. * Purpose: To sort a randomly generated 8 numbers via bubble sort.
  5. */
  6. package edu.hdsb.rbhs.ics3u.closs.u4;
  7.  
  8. public class BubbleSort {
  9.  
  10. public static int[] data = new int[8];
  11. public static int numberOfSwaps;
  12. public static int numberOfComparisons;
  13.  
  14. public static void randomizingArray() {
  15.  
  16. for (int i = 0; i < data.length; i++) {
  17. data[i] = (int) (1000 * Math.random()) + 1;
  18.  
  19. System.out.print(data[i] + ", ");
  20. }
  21. }
  22.  
  23. public static void bubbleSort() {
  24.  
  25. for (int pass = 0; pass < data.length - 1; pass++) {
  26. for (int i = 0; i < data.length - 1; i++) {
  27. numberOfComparisons = numberOfComparisons + 1;
  28. while (data[i] > data[i + 1]) {
  29. swap( data, i, i + 1 );
  30. numberOfSwaps = numberOfSwaps + 1;
  31. }
  32. }
  33. }
  34. }
  35.  
  36. public static void swap(int[] a, int i, int j) {
  37.  
  38. int temp;
  39. temp = data[i];
  40. data[i] = data[j];
  41. data[j] = temp;
  42.  
  43. }
  44.  
  45. public static void main(String[] args) {
  46. System.out.println("Unsorted data: ");
  47. randomizingArray();
  48. bubbleSort();
  49.  
  50. System.out.println("\n\nSorted data: ");
  51.  
  52. for (int i = 0; i < data.length; i++) {
  53. System.out.print(data[i] + ", ");
  54. }
  55.  
  56. System.out.println("\n");
  57. System.out.println("Number of Comparisons: " + numberOfComparisons + "\n" + "Number of Swaps: " + numberOfSwaps);
  58.  
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement