Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. for(k=0;k<array.length-1;k++){
  2. if(array[k] > array[k+1]){
  3. int temp = array[k];
  4. array[k] = array[k+1];
  5. array[k+1] = temp;
  6. }
  7. }
  8.  
  9. for(i=array.length-1;i>=0;i--){
  10. for(k=0;k<i;k++){
  11. if(array[k] > array[k+1]){
  12. int temp = array[k];
  13. array[k] = array[k+1];
  14. array[k+1] = temp;
  15. }
  16. }
  17. }
  18.  
  19. public static void bubbleSort(int[] array){
  20. for (int i = 0; i < array.length - 1; i++) {
  21. for (int j = 0; j < array.length - i - 1; j++) {
  22. if(array[j] < array[j+1]){
  23. int tmp = array[j];
  24. array[j] = array[j+1];
  25. array[j+1] = tmp;
  26. }
  27. }
  28. }
  29. }
  30.  
  31. procedure bubbleSort( A : list of sortable items )
  32. n = length(A)
  33. repeat
  34. newn = 0
  35. for i = 1 to n-1 inclusive do
  36. if A[i-1] > A[i] then
  37. swap(A[i-1], A[i])
  38. newn = i
  39. end if
  40. end for
  41. n = newn
  42. until n = 0
  43. end procedure
  44.  
  45. //array of integer to be sorted
  46. int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
  47. //repeat until we're done sorting
  48. while (true){
  49. //flag to check if we did swap number(s)
  50. boolean didSort=false;
  51. /*
  52. * this inner loop is being used to find numbers that need to be
  53. * swapped and then help in swapping them
  54. */
  55. for(int count=0;count<arrayToSort.length-1;count++){
  56. //check if we need to swap
  57. if(arrayToSort[count]>arrayToSort[count+1]){
  58. int temp=arrayToSort[count+1];
  59. arrayToSort[count+1]=arrayToSort[count];
  60. arrayToSort[count]=temp;
  61. //set our swap flag so that we will know that we did swap
  62. didSort=true;
  63. }
  64.  
  65. }
  66.  
  67. //check we did a swap in our last inner loop iteration if not will
  68. //be done sorting, then break the outer loop
  69. if(!didSort){
  70. break;
  71. }
  72. }
  73.  
  74. //let's print the sorted array.
  75. for(int i=0;i<arrayToSort.length;i++){
  76. System.out.print(arrayToSort[i]+", ");
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement