Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. Algorithm: Bubble Sort
  2. Input: Array ary of sortable values
  3. Output:s Array ary in ascending order
  4. ***************************/
  5. import java.util.Scanner;
  6.  
  7. public class BubbleSortExample {
  8.  
  9. static void bubbleSort(int[] arr) {
  10. int n = arr.length;
  11. int temp = 0;
  12. boolean isSorted = false;
  13.  
  14. // while ( array ary is not sorted )
  15. while (!isSorted){
  16. isSorted = true; // Sorted when we loop without swap
  17.  
  18. // for ( each adjacent pair of items )
  19. for(int j=1; j <= n-1; j++){
  20.  
  21. // if ( the pair of items are out of order )
  22. if(arr[j-1] < arr[j]){
  23.  
  24. // swap the pair of items
  25. temp = arr[j-1];
  26. arr[j-1] = arr[j];
  27. arr[j] = temp;
  28. isSorted = false;
  29. }
  30. }
  31. }
  32.  
  33. }
  34.  
  35. public static void main(String[] args) {
  36. int arr[] ={3,60,35,2,45,320,5};
  37.  
  38. System.out.println("Array Before Bubble Sort");
  39. for(int i=0; i < arr.length; i++){
  40. System.out.print(arr[i] + " ");
  41. }
  42. System.out.println();
  43.  
  44. bubbleSort(arr);//sorting array elements using bubble sort
  45.  
  46. System.out.println("Array After Bubble Sort");
  47. for(int i=0; i < arr.length; i++){
  48. System.out.print(arr[i] + " ");
  49. }
  50.  
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement