Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. public static void swap(int[] array, int posA, int posB) {
  2. /*
  3. Description: Swaps two values in an int array
  4. Parameters: int array of values and positions of elements to be swapped
  5. Returns: void
  6. */
  7. // Task: Complete method code
  8. int tmp;
  9.  
  10. tmp = array[posA];
  11. array[posA] = array[posB];
  12. array[posB] = tmp;
  13. }
  14.  
  15.  
  16. public static void bubbleSort(int[] array) {
  17. /*
  18. Description: Sorts a int array using bubblesort algoritm
  19. Parameters: int array of values to be sorted
  20. Returns: void
  21. */
  22. // Task: Complete method code and count number of comparisons and swaps
  23.  
  24. int comp = 0, swaps = 0, posA, posB;
  25.  
  26. for (int out = array.length - 1; out > 0; out--) {
  27. comp++;
  28. for (int in = 0; in < out; in++) {
  29. if (array[in] > array[in + 1]) {
  30. posA = in;
  31. posB = in + 1;
  32.  
  33. swap(array, posA, posB);
  34. swaps++;
  35. }
  36. }
  37. }
  38. System.out.println("The array is now sorted, the amount of comparisons is " + comp + ", and the number of swaps is " + swaps);
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement