バブルソート(processing)
バブルソート(processing)
Bubble_sort[] sort_val; int[] val = {8,3,5,2,9,7,9,1}; //ソートする値 int text_size = 40; int[] ptx = new int[val.length]; int count = 0; boolean move = true; int sort_loop = 0; void setup(){ textAlign(CENTER, CENTER); frameRate(60); size(500, 300); fill(0); strokeWeight(text_size/10); textSize(text_size); sort_val = new Bubble_sort[val.length]; for(int i=0; i<val.length; i++){ ptx[i] = width / (val.length*2) * (i*2+1); sort_val[i] = new Bubble_sort(val[i], ptx[i]); } } void draw(){ background(255); for(int i=0; i<val.length; i++) sort_val[i].draw(); //数値表示 if(sort_val[count].val > sort_val[count+1].val && move == true){ //隣接する左の値が大きければ座標を交換する sort_val[count].pt_x = sort_val[count+1].pt_now; sort_val[count+1].pt_x = sort_val[count].pt_now; move = false; } if(sort_loop < val.length) { //比較する数値の上に線を引く line(sort_val[count].pt_now, height/2-text_size/2, sort_val[count].pt_now, height/2-text_size*5/4); line(sort_val[count+1].pt_now, height/2-text_size/2, sort_val[count+1].pt_now, height/2-text_size*5/4); line(sort_val[count].pt_now, height/2-text_size*5/4, sort_val[count+1].pt_now, height/2-text_size*5/4); } if(move == true || (sort_val[count].pt_x == sort_val[count].pt_now && sort_val[count+1].pt_x == sort_val[count+1].pt_now)){ //数値の位置交換を終えたかの判定 if(move == false) { //数値交換(隣接する左の値が小さい場合この分岐に入らない) int swap = sort_val[count].val; sort_val[count].val = sort_val[count+1].val; sort_val[count+1].val = swap; sort_val[count].pt_x = sort_val[count+1].pt_now; sort_val[count+1].pt_x = sort_val[count].pt_now; sort_val[count].pt_now = sort_val[count].pt_x; sort_val[count+1].pt_now = sort_val[count+1].pt_x; move = true; } count++; if(count > val.length - 2 - sort_loop) { //1周終えたかどうか判定 count = 0; if(sort_loop < val.length) sort_loop++; } } } class Bubble_sort { //数値表示 int val, pt_now, pt_x; Bubble_sort(int val, int pt_now){ this.val = val; this.pt_now = this.pt_x = pt_now; } void draw(){ if(pt_now < pt_x) pt_now++; if(pt_now > pt_x) pt_now--; text(val, pt_now, height/2); } }