Javaswing sorting Animation

Source: Internet
Author: User

Sorting animation has been done for a while, and I think it is necessary to record it.

Let's rest and get back to business.


Specifically, there are four sorting animations: insert sorting, Bubble sorting, select sorting, and fast sorting.

The reason for this sort animation is that I used to learn sorting and watched the sort animated video on YouTube, which was very shocking.

Later, I learned the Java Process and gradually discovered that this could be done. It was really hard work and hard work.


First, this program is most important to represent the size of the number in a bar chart. The larger the number, the higher the bar chart.

Here I define a histogram class, which is mainly used to draw a bar chart based on the numbers in the array.

package Sorting_Animation;import javax.swing.JPanel;import java.awt.*;public class Histogram extends JPanel {private int[] count;private int index1;   //The index of red barprivate int index2;   //The index of red barprivate static final int length = 100; private int maxCount;private int begin;private int end;/**Set the count and two red bar and display histogram*/public void showHistogram(int[] count, int index1, int index2){this.index1 = index1;this.index2 = index2;this.count = count;repaint();}/**Set the count and one red bar and display histogram */public void showHistogram(int[] count, int index1){this.index1 = index1;this.count = count;this.begin = 0;this.end = count.length;;repaint();}/**Set the count and display histogram */public void showHistogram(int count[]){this.count = count;this.begin = 0;this.end = count.length;repaint();}/**Show the merge histogram */public void showMergeHistogram(int count[],int index1,int begin,int end){this.begin = begin;this.end = end;this.count = count;repaint();}/**Define the histogram*/public Histogram(){setCount();setMaxCount(count);showHistogram(count);}public int[] getCount(){return count;}public static int getLength(){return length;}/**Set the random elements*/public void setCount(){count = new int[length];boolean flag=false;    int temp;    int index1 = 0;while(index1 < length){    temp = (int)(Math.random()*length)+1;    //Check the same element    for(int j=0;j<index1;j++){    if(temp == count[j]){    flag=true;    break;    }    else{    flag = false;    }    }        if(!flag )    count[index1++] = temp;}    }/** Set the worst elements */public void setWorstCount(){count = new int [length];while(index1 < length){count[index1++] = 100 - index1;}}/**Paint the histogram */protected void paintComponent(Graphics g){if(count == null){return;  //No display if count is null}super.paintComponent(g);//Find the panel size and bar with interval dynamicallyint width = getWidth();int height = getHeight();int interval = (width - 40)/length;//x is the start position for the first bar in the histogramint x = 30;for(int i = 0 ;i< begin - 1; i++){x += interval;}//Draw the fillRect for(int i = begin; i<end; i++){//Find the bar heightint barHeight =(int)(((double)count[i]/(double)maxCount)*(height - 55));//Get the index1if(i == index1){g.setColor(Color.red);   g.fillRect(x, height-barHeight, interval, barHeight);x += interval;   //Make next bar blueindex1 = -1;}//Get the index2if( i == index2){g.setColor(Color.red);   g.fillRect(x, height-barHeight, interval, barHeight);x += interval;   //Make next bar blueindex2 = -1;}//Display a barg.setColor(Color.green);g.fillRect(x, height-barHeight, interval, barHeight);//Move x for displaying the next characterx += interval;}}private void setMaxCount(int count[]){//Find the maximum count.  The maximum count has the highest barint maxCount = 0;for(int i = 0; i < length; i++){if(maxCount < count[i])maxCount = count[i];}this.maxCount = maxCount;}}

Here, index1 and index2 are used to indicate the current position of sorting. We will draw it as a red bar, and others as a green bar.

Where

int interval = (width - 40)/length;

Is used to determine the width of each bar

int barHeight =(int)(((double)count[i]/(double)maxCount)*(height - 55));

Barheight determines the bar height based on the values of each element in the array.

With these elements, You can traverse the Count array to draw a bar chart. In fact, this is the most important part.

The quality of this part directly affects the program effect.


With the bar chart class, it is basically half done.

Next we will introduce the Sorting Algorithm to be done, and let these sorting "draw your own sorting process"

Package sorting_animation; import Java. util. concurrent. *; public class sorting implements runnable {private histogram inserthistogram = new histogram (); Private histogram bubblehistogram = new histogram (); Private histogram selectionhistogram = new histogram (); private Static histogram quickhistogram = new histogram (); Private Static histogram mergehistogram = new histogram (); Private Static int mergecoun T []; // Private Static int Index = 0; // The merge sort first indexpublic void run () {executorservice executor = export cute (new export cute (New quicksorttask (); // executor.exe cute (New mergesorttask (); executor. shutdown (); While (! Executor. isterminated () {}} public histogram getinserthistogram () {return inserthistogram;} public histogram blocks () {return bubblehistogram;} public histogram getselectionhistogram ;} public histogram getquickhistogram () {return quickhistogram;} public histogram getmergehistogram () {return mergehistogram;}/** the insertion sort task class */class implements runnable {public void run () {int count [] = inserthistogram. getcount (); int I = 0; Int J = 0; int V = 0; for (I = 1; I <count. length; I ++) {try {v = count [I]; j = I-1; while (j> = 0 & COUNT [J]> V) {inserthistogram. showhistogram (count, J); thread. sleep (20); count [J + 1] = count [J]; j --;} count [J + 1] = V; inserthistogram. showhistogram (count);} catch (interruptedexception ex) {ex. printstacktrace () ;}}}/ ** the bubble sort task class */class bubblesorttask implements runnable {public void run () {int count [] = bubblehistogram. getcount (); For (INT I = 1; I <count. length; I ++) {for (Int J = 0; j <count. length-I; j ++) {try {bubblehistogram. showhistogram (count, J); thread. sleep (20); If (count [J]> count [J + 1]) {int temp = count [J]; count [J] = count [J + 1]; count [J + 1] = temp;} catch (interruptedexception ex) {ex. printstacktrace () ;}} bubblehistogram. showhistogram (count) ;}}/** the selection sort task class */class selectionsorttask implements runnable {public void run () {int count [] = selectionhistogram. getcount (); For (INT I = count. length-1; I> = 0; I --) {int max = I; for (Int J = I-1; j> = 0; j --) {try {selectionhistogram. showhistogram (count, J); thread. sleep (20); If (count [J]> count [Max]) {max = J ;}} catch (interruptedexception ex) {ex. printstacktrace () ;}} int temp = count [I]; count [I] = count [Max]; count [Max] = temp; selectionhistogram. showhistogram (count) ;}}/ ** the quicksort task class */class quicksorttask implements runnable {public void run () {int count [] = quickhistogram. getcount (); quicksort (count, 0, Count. length-1) ;}}/** the mergesort task class */class mergesorttask implements runnable {public void run () {int count [] = mergehistogram. getcount (); mergecount = new int [count. length]; system. arraycopy (count, 0, mergecount, 0, Count. length); mergesort (count, 0, Count. length-1) ;}}/** the Quick Sort Method */Private Static void quicksort (int A [], int first, int last) {int I = first + 1; int J = last; If (first <last) {int P = A [first]; do {try {While (I <last & A [I] <= P) {if (I <last) {quickhistogram. showhistogram (A, I, j); thread. sleep (20);} I ++;} while (j> first & A [J]> = P) {If (j> first) {quickhistogram. showhistogram (A, I, j); thread. sleep (20);} j --;} if (I <= J) {int temp1 = A [I]; A [I] = A [J]; A [J] = temp1; // quickhistogram. showhistogram (a); // thread. sleep (100) ;}} catch (interruptedexception ex) {ex. printstacktrace () ;}} while (I <j); // swap (A [J], a [first], temp); int temp2 = A [J]; A [J] = A [first]; A [first] = temp2; quickhistogram. showhistogram (a); quicksort (A, first, J-1); quicksort (A, J + 1, last );}} /** the merge sort method */Private Static int [] mergesort (INT [] data, int start, int end) {If (START = end-1 | start = end) {If (START = data. length) {int [] T = new int [] {data [start-1]}; return t ;} else {int [] T = new int [] {data [start]}; return t ;}int [] M1 = mergesort (data, start, (start + end) /2); int [] m2 = mergesort (data, (start + end)/2, end); int [] merge = Merge (M1, M2, start, end ); return merge;} Private Static int [] merge (INT [] dataa, int [] datab, int start, int end) {If (dataa. length = 0) {return datab;} else if (datab. length = 0) {return dataa;} int [] orderdata = new int [dataa. length + datab. length]; int Indexa = 0, indexb = 0; For (INT I = 0; I <orderdata. length; I ++) {If (Indexa> = dataa. length) {orderdata [I] = datab [indexb ++]; mergehistogram. showhistogram (orderdata, I); try {thread. sleep (20);} catch (interruptedexception e) {// todo automatically generates Catch Block E. printstacktrace () ;}} else if (indexb> = datab. length) {orderdata [I] = dataa [Indexa ++]; mergehistogram. showhistogram (orderdata, I); try {thread. sleep (20);} catch (interruptedexception e) {// todo automatically generates Catch Block E. printstacktrace () ;}} else if (dataa [Indexa]> datab [indexb]) {orderdata [I] = datab [indexb ++]; mergehistogram. showhistogram (orderdata, I); try {thread. sleep (20);} catch (interruptedexception e) {// todo automatically generates Catch Block E. printstacktrace () ;}} else {orderdata [I] = dataa [Indexa ++]; mergehistogram. showhistogram (orderdata, I); try {thread. sleep (20);} catch (interruptedexception e) {// todo automatically generates Catch Block E. printstacktrace () ;}}return orderdata ;}}

Each sorting algorithm corresponds to a histogram class, which implements the runnable interface,

Next, we only need to do some operations in the sorting algorithm to traverse the current element every time in the sorting algorithm,

We will draw a bar chart corresponding to the overall count array and draw the current bar in red,

Then let the thread sleep for 20 milliseconds, such as insertion sorting

Public void run () {int count [] = inserthistogram. getcount (); int I = 0; Int J = 0; int V = 0; for (I = 1; I <count. length; I ++) {try {v = count [I]; j = I-1; while (j> = 0 & COUNT [J]> V) {inserthistogram. showhistogram (count, J); // draw the current bar chart thread. sleep (20); // Let the thread sleep for 20 mscount [J + 1] = count [J]; j --;} count [J + 1] = V; inserthistogram. showhistogram (count);} catch (interruptedexception ex) {ex. printstacktrace ();}}}

The Merge Sorting requires additional array space. In my design system, it is difficult to draw a Merge Sorting Process.

Here, I would like to help you with this.

The next step is multi-thread control.

private Histogram insertHistogram = new Histogram();private Histogram bubbleHistogram = new Histogram();private Histogram selectionHistogram = new Histogram();private static Histogram quickHistogram = new Histogram();private static Histogram mergeHistogram = new Histogram(); private static int mergeCount[];//private static int index = 0;    //The merge sort first indexpublic void run(){ExecutorService executor = Executors.newCachedThreadPool();executor.execute(new InsertSortTask());executor.execute(new BubbleSortTask());executor.execute(new SelectionSortTask());executor.execute(new QuickSortTask());//executor.execute(new MergeSortTask());executor.shutdown();while(!executor.isTerminated()){}}

The final part is the overall screen layout, which draws the four sort animations into the frame.

Package sorting_animation; import Java. AWT. *; import javax. swing. *; import Java. AWT. event. *; public class sortinganimation extends jframe {private jbutton jbtstart = new jbutton ("START"); Private sorting sort = new sorting (); Private authorinfo author = new authorinfo (); public sortinganimation () {final thread = new thread (SORT); jpanel Panel1 = new jpanel (New gridlayout (,); histogram inserthistogram = sort. getinserthistogram (); histogram bubblehistogram = sort. getbubblehistogram (); histogram selectionhistogram = sort. getselectionhistogram (); histogram quickhistogram = sort. getquickhistogram (); histogram mergehistogram = sort. getmergehistogram (); inserthistogram. setborder (borderfactory. createtitledborder ("insertion sort"); bubblehistogram. setborder (borderfactory. createtitledborder ("bubble sort"); selectionhistogram. setborder (borderfactory. createtitledborder ("selection sort"); quickhistogram. setborder (borderfactory. createtitledborder ("Quick Sort"); // mergehistogram. setborder (borderfactory. createtitledborder (// "merge sort"); panel1.add (batch); panel1.add (batch); panel1.add (selectionhistogram); panel1.add (quickhistogram); // panel1.add (mergehistogram ); jpanel panel2 = new jpanel (); panel2.add (jbtstart); setlayout (New borderlayout (); add (author, borderlayout. north); add (Panel1, borderlayout. center); add (panel2, borderlayout. south); jbtstart. addactionlistener (New actionlistener () {public void actionreceivmed (actionevent e) {thread. start (); jbtstart. setenabled (false) ;}});} public static void main (string [] ARGs) {// todo Automatic Generation Method stub jframe = new sortinganimation (); frame. settitle ("sorting Animation"); frame. setsize (1000,700); frame. setlocationrelativeto (null); frame. setdefaclocloseoperation (jframe. exit_on_close); frame. setvisible (true );}}

Here, my sorting animation is complete.

Thank you for your reference.

Attached with relevant information

Code

Quick Sort animation can run jar

Four sort animations can run jar

Fast-track animated videos

Four sort animated videos

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.