Random Array & Bubble Sort (Programming beginner)

(This may seem a little basic but..) I want to create an array with a random size and filled with random integers between 1 and 100. I then want to be able to sort them using bubble sort. I'm really stuck and would appreciate if someone could point me in the right direction. here's what I have so far but it prints out some crazy answers.

float [] array = new float [100];
float temp = 0;
void setup() 
{ 
  for (int a = 0; a< array.length; a++)
  {
    array[a]= int(random (10, 100));
  }
}
void draw () 
{ 
  for (int s =0; sarray[d+1]) {
        temp = array[d+1];
        array[d+1] =temp;
      }
    }
  }
  println(  array);
 
Tagged:

Answers

  • Apologies about code formatting should look easier on the eye now

  • edited December 2015 Answer ✓
    1. If you want to have integers, you should use an int-array instead of float.

    2. If you want an array of random-size, you should not initialize one with a length of 100.

    3. You fill the array with random numbers between 10 and 100 instead of 1 and 100.

    4. You should move you sorting-algorithm to setup(), it makes no sense to repeat this step. Once the array is sorted, it would not change anymore.

    5. The syntax of your second for-loop is wrong, look at your first one to see how it should look like.

    6. The println(array); is outside of any function, that will throw an error, move it to setup() too.

    So your code could look kind of like this:

    // declare array
    int [] array;
    
    void setup() {
      // initialize array with a random size, 
      // (you did not specify the range, i just picked 100)
      array = new int [ int(random(100)) ];
    
      // fill array with random numbers
      for (int a = 0; a< array.length; a++)
      {
        array[a]= int(random (1, 101));
      }
    
      /*
        sort your array here
      */
    
      printArray(array);
    }
    

    I left the sorting part out, so you can try to solve it on your own. If you need more information on bubble-sort, wikipedia is a nice source.

  • OMG YES Thank you soon much!!!!!!!!

Sign In or Register to comment.