Advertisement
LoganBlackisle

BubbleSort

Jun 17th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. package prep_18_sortering;
  2.  
  3. public class BubbleSort {
  4. // Bubble Sort is the simplest sorting algorithm that works by repeatedly
  5. // swapping the adjacent elements if they are in wrong order
  6.  
  7. public void bubbleSort(int arr[]) {
  8. int n = arr.length;
  9. for (int i = 0; i < n - 1; i++) {
  10. for (int j = 0; j < n - i - 1; j++) {
  11. if (arr[j] > arr[j + 1]) {
  12. // swap arr[j+1] and arr[i]
  13. int temp = arr[j];
  14. arr[j] = arr[j + 1];
  15. arr[j + 1] = temp;
  16. }
  17. }
  18. }
  19. }
  20.  
  21. /* Prints the array */
  22. public void printArray(int arr[]) {
  23. int n = arr.length;
  24. for (int i = 0; i < n; ++i) {
  25. System.out.print(arr[i] + " ");
  26. }
  27. System.out.println();
  28. }
  29.  
  30. // Driver method to test above
  31. public static void main(String args[]) {
  32. BubbleSort ob = new BubbleSort();
  33. int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
  34. ob.bubbleSort(arr);
  35. System.out.println("Sorted array");
  36. ob.printArray(arr);
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement