Advertisement
SakoJina

Bubble Sort

Mar 1st, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. int arraySize = 500;
  2. int count = 0;
  3. boolean sorted;
  4. int swapped = 0;
  5. int access = 0;
  6. int max;
  7.  
  8. int[] collection;
  9.  
  10. void setup()
  11. {
  12.   //size(1080, 600);
  13.   stroke(0,255,0);
  14.   strokeWeight(2);
  15.   frameRate(60);
  16.   background(0);
  17.  
  18.   //size(500,300);
  19.   fullScreen();
  20.  
  21.   collection = new int[arraySize];
  22.  
  23.   for(int i = 0; i < collection.length; i++)
  24.   {
  25.     collection[i] = int(random(collection.length));
  26.   }
  27.  
  28.   max = collection.length;
  29.  
  30. }
  31.  
  32. void draw()
  33. {
  34.  
  35.   background(0);
  36.   text(swapped, 10,10);
  37.   text(access, 10, 20);
  38.   text(max,10,30);
  39.    
  40.   if(isSorted())
  41.   {
  42.         for(int i = 0; i < collection.length; i++)
  43.         {
  44.         collection[i] = int(random(collection.length));
  45.         }
  46.         swapped = 0;
  47.         access = 0;
  48.         max = collection.length;
  49.   }
  50.  
  51.   for(int i = 0; i < collection.length; i++)
  52.   {  
  53.      
  54.      float x = map(i,0,collection.length,25,width - 25);
  55.      
  56.      stroke(255,map(collection[i],getLowest(),getHighest(),0,150),0);
  57.      
  58.      line(x, height, x, height - map(collection[i],0,collection.length,0,height));  
  59.      
  60.   }
  61.  
  62.   bubbleSort(collection);
  63.  
  64. }
  65.  
  66. int getHighest()
  67. {
  68.  
  69.   int highest = 0;
  70.  
  71.   for(int i = 0; i < collection.length; i++)
  72.   {  
  73.     if(collection[i] > highest)
  74.     highest = collection[i];
  75.   }
  76.  
  77.   return highest;  
  78. }
  79.  
  80. int getLowest()
  81. {
  82.  
  83.   int lowest = getHighest();
  84.  
  85.   for(int i = 0; i < collection.length; i++)
  86.   {  
  87.     if(collection[i] < lowest)
  88.     lowest = collection[i];
  89.   }
  90.  
  91.   return lowest;  
  92. }
  93.  
  94. boolean isSorted()
  95. {
  96.   for(int i = 0; i < collection.length - 1; i++)
  97.   {  
  98.     if(collection[i] > collection[i + 1])
  99.     return false;
  100.   }  
  101.   return true;
  102. }
  103.  
  104. void bubbleSort(int[] a)
  105. {
  106.   for(int i = 0; i < max -1; i++)
  107.   {      
  108.      if(a[i] > a[i + 1])
  109.      {
  110.        int temp = 0;
  111.        temp = a[i];
  112.        a[i] = a[i + 1];
  113.        a[i + 1] = temp;
  114.        swapped++;
  115.      }
  116.      access++;
  117.   }
  118.   max --;
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement