Advertisement
Guest User

bubble_sort

a guest
Jan 28th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #define SIZE 8
  2.  
  3. int arr[SIZE];
  4. int i;
  5. int j;
  6. bool wasPermutation;
  7. int randomValue;
  8. int tmp;
  9. bool sortingFinished;
  10.  
  11. // generate random in range [minV, maxV]
  12. inline genRandom(minV, maxV) {
  13. randomValue = minV;
  14. do
  15. :: (randomValue == maxV) -> break; // increased up to max value => stop
  16. :: else ->
  17. if
  18. :: select(tmp : 5 .. 15);
  19. randomValue = randomValue + tmp; // randomly increment
  20. :: select(tmp : 1 .. 100);
  21. randomValue = randomValue - tmp; // randomly decrement
  22. :: break; // or stop
  23. fi;
  24. od;
  25. return randomValue;
  26. }
  27.  
  28. inline swap(i1, i2) {
  29. tmp = arr[i1];
  30. arr[i1] = arr[i2];
  31. arr[i2] = tmp;
  32. }
  33.  
  34. active proctype Main() {
  35. // fill initial array
  36. for (i : 0..(SIZE-1)) {
  37. arr[i] = genRandom(0, 100);
  38. }
  39. printf("Generated array: [");
  40. for (i : 0..(SIZE-1)) {
  41. printf("%d ", arr[i]);
  42. }
  43. printf("]\n");
  44.  
  45. printf("Start sorting...\n");
  46. wasPermutation = true;
  47. sortingFinished = false;
  48. do
  49. :: (wasPermutation) ->
  50. wasPermutation = false;
  51. for (j : 0..(SIZE-2)) {
  52. if
  53. :: (arr[j] > arr[j+1]) ->
  54. swap(j, j+1);
  55. wasPermutation = true;
  56. :: else -> skip;
  57. fi;
  58. }
  59. :: else -> break;
  60. od;
  61. sortingFinished = true;
  62.  
  63. printf("Sorted array: [");
  64. for (i : 0..(SIZE-1)) {
  65. printf("%d ", arr[i]);
  66. }
  67. printf("]\n");
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement