Posted By

rnavanee on 09/16/13


Tagged

algorithm sorting


Versions (?)

My Bubble Sort


 / Published in: Java
 

URL: http://www.algolist.net/Algorithms/Sorting/Bubble_sort

Bubble Sort - Algorithm

1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
2. If at least one swap has been done, repeat step 1.
  1. import java.util.Arrays;
  2.  
  3.  
  4. /**
  5.  * Ref: http://www.algolist.net/Algorithms/Sorting/Bubble_sort
  6.  *
  7.  * Algorithm
  8.  * 1. Compare each pair of adjacent elements from the beginning
  9.  * of an array and, if they are in reversed order, swap them.
  10.  * 2. If at least one swap has been done, repeat step 1.
  11.  *
  12.  *
  13.  */
  14. public class MyBubbleSort {
  15.  
  16. public static void main(String[] args) {
  17. int[] data = {5,1,12,-5,16};
  18. System.out.println(Arrays.toString(data));
  19. new MyBubbleSort().sortData(data);
  20. System.out.println(Arrays.toString(data));
  21. }
  22.  
  23. private void sortData(int[] data) {
  24. boolean swapDone = false;
  25. do {
  26. swapDone = false;
  27. for (int i=0; i<data.length-1; i++) {
  28. if (data[i]>data[i+1]) {
  29. swapDone = true;
  30. int tmp = data[i];
  31. data[i] = data[i+1];
  32. data[i+1] = tmp;
  33. }
  34. }
  35. } while (swapDone==true);
  36. }
  37. }

Report this snippet  

You need to login to post a comment.