Testing Arrays in Processing

Today I wanted to see how the Processing environment can handle more advanced code then shapes. I made a program to test processings abilities and mine, here is the output of the arrays methods below:

Unsorted:
[2][5][3][1][4]
Shuffled:
[3][2][1][5][4]
Sorted:
[1][2][3][4][5]
Flipped:
[5][4][3][2][1]

I made all the methods myself, There are 4 methods not including the main one. The first one prints out the array, it has a loop that prints one index at a time from the array. The next one is to shuffle the array. It picks 2 cards, swaps them, then does that 1000 times. the third one sorts the array with bubble sort, bubble sort is very had to describe so you should look on google for a explanation. Finally there is a flip method which swaps the one on the far right and left, and then the second to last and second to first and so on. I’ll paste in my code below:

import java.util.*;

public static void main(String args[]){
  System.out.println(“Unsorted:”); 
  int[] arr = {2,5,3,1,4};
  printArr(arr);
  System.out.println(“Shuffled:”);
  shuffleArr(arr);
  printArr(arr);
  System.out.println(“Sorted:”);
  sortArr(arr);
  printArr(arr);
  System.out.println(“Flipped:”);
  flipArr(arr);
  printArr(arr);
}

public static void printArr(int[] a){
 
  for(int i =0; i<=a.length-1; i++){
    System.out.print(“[“+a[i]+”]”);
  }
  System.out.println();
}

public static void shuffleArr(int[] a){
  Random r = new Random();
  int temp1 = 0;
  int r1=0;
  int r2=0;
  for(int i =0; i <=1000; i++){
    r1 = r.nextInt(a.length);
    r2 = r.nextInt(a.length);
    temp1=a[r1];
    a[r1]=a[r2];
    a[r2]=temp1;
   }
}

public static int[] sortArr(int[] a){
 
  int temp = 0;
  int j =0;
  boolean unsorted = true;
  while(unsorted){
    unsorted = false; 
    j++;
    for(int i =0; i<a.length-j; i++){
        if(a[i] > a[i+1]){
          temp = a[i];
          a[i]=a[i+1];
          a[i+1]=temp;
          unsorted = true;
        }
      }
    }
  
   return a;
}

public static int[] flipArr(int[] a){
  int rightEnd= a.length-1;
  int leftEnd=0;
  int temp =0;
  while(leftEnd<rightEnd){
    temp =a[leftEnd];
    a[leftEnd]=a[rightEnd];
    a[rightEnd]=temp;
    rightEnd–;
    leftEnd++;
  }
  return a;
}

Leave us a reply