Tuesday, August 31, 2010

JAVA : Sorting Animations

JAVA Sorting Animations:

Sorting animations is a Java application that shows how a sorting alogrithm works by graphical animations. In this Java application working of four sorting alogrithm are shown through animations. 




!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!!
Selection Sort:

Selection Sort is a very simple algorithm but it is inefficent on large lists.
The Selection algorithm works as follows:
  1. Find the minimum value in the list
  2. Swap it with the value in the first position
  3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)
  JAVA Code for Selection Sort Algorithm
//Selection sort algorithm method 
  public List sort(List a) throws Exception {
int max,min,pos=0;
     boolean swapped=false;
     for(int i=0; i < a.size(); i++){
              swapped=false;
              max=min=a.get(i);
              for(int j=i+1; j < a.size() ; j++){
                                     if(min>a.get(j)){
                                                 min=a.get(j);
  pos=j;
 swapped=true;
                                     }
               }

  if(swapped){
                    a.set(i, min);
                    a.set(pos, max);    
              }
      }
return a;
}//end of sort method

Selection sort algorithm performance:-
  • Worst case performance -
  • Best case performance -
  • Average case performance-
Bubble Sort:

Bubble sort is a sorting algorithm that works by repeatedly traversing through the list and compares the current element with the next one and swap them if they appears in wrong order. Traversing through the list is repeated until no swaps are needed. To known that the list is sorted we need to have one traversing through the list with no swap that means we need to traverse the list one more time even if the list is already sorted.


  JAVA Code for Bubble Sort Algorithm
 //bubble sort algorithm method
 public List sort(List a) throws Exception {
      boolean swapped =false;
for (int i = a.size()-1; i >= 0; i--) {
                  swapped = false;
                 for (int j = 0; j < i; j++) {

    if (a.get(j) > a.get(j+1)) {
                                    int T = a.get(j);
                                    a.set(j, a.get(j+1));
                                     a.set(j+1, T);
   swapped = true;
}
                    }
                 if(!swapped){
                           break;
}
}
return a;
}//end of sort method


Bubble Sort Algorithm Performance:-
  • Worst case performance -
  • Best case performance - n
  • Average case performance-
Insertion sort:

Insertion sort is good only for sorting small arrays (usually less than 100 items). In fact, the smaller the array, the faster insertion sort is compared to any other more advance  sorting algorithm such as Qucik sort.

  JAVA Code for Insertion Sort Algorithm
//insertion sort algorithm method 
 public List sort(List a) throws Exception {
       boolean swapped =false;
       int i, j, temp;
        for (i = 1; i < a.size(); i++) {
                temp = a.get(i);
                j = i;
              while (j > 0 && a.get(j - 1) > temp) {
                    a.set(j, a.get(j - 1));
                     j--;
               }
             a.set(j, temp);
       }
     
return a;
}//end of sort method



Insertion Sort Algorithm Performance:-
  • Worst case performance -
  • Best case performance - n
  • Average case performance-
Quick Sort:

Quick sort is a faster in practice and more advance sorting alogrithm as compare to some other simple algorithm such as Selection sort or Bubble sort.
  JAVA Code for Quick Sort Algorithm
//Quick sort algorithm method 
 public List sort(List a, int left, int right) throws Exception {
int mid,tmp,i,j;
 
  mid = a.get((left + right)/2);
  
  do {
       while(a.get(i) < mid){
          i++;
          
       }
      while(mid < a.get(j)){
          j--;
          
      }
      if (i <= j) {
          tmp = a.get(i);
          a.set(i, a.get(j));
          a.set(j, tmp);
          i++;
          j--;
      }
  } while (i <= j);
  if (left < j){
  sort(a,left,j);
  }
  if (i < right){ 
  sort(a,i,right);
  }
 
     return a;
}//end of sort method


Quick Sort Algorithm Performance:-
  • Worst case performance   -
  • Best case performance -       nlogn
  • Average case performance- nlogn

Download Files Here:


Sunday, August 22, 2010

JAVA : Typing Test

Typing Test 
Manoj Tiwari


How fast can you type? Find out with Typing Test JAVA application.
Select a time and text to type. After completing the test, you will see your typing speed, accuracy and net speed.




!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!
Typing Test  is a Java program that tests your typing speed. You get a number of tests to choose from. Typing Test program counts the number of total words and worng words and on basis of that gives result.


Instructions

1. Choose a Test from List. 
2. Choose the time for test.
3. Click "Start" Button.
4. Typing test will appear. Time will start when you start typing.
5. A mistake done once can not be corrected (i.e. you cannot correct the Word once you hit the space bar).
6. Keep on typing until the time passes or hit the Finish Button.
7. Your Result will be displayed.

Scoring

Typing Test program will count the number of the correctly typed words and wrong typed word. If you mistype a word, it will be highlighted. Result has three parts 
1. Gross speed(total number of words typed divide by total time of test) 
2. Accuracy (Percentage of Correctly typed word out of  total number of words typed )
3. Net Speed (number of words correctly typed divide by total time of test)


Files

TestPage.java and TestPageapp.java:-
TestPage.java is the main class for running Typing Test as System application and TestPageapp.java is the main class for running Typing Test as Web pages(Applet).
These classes have the code for Making a window, setting Look and Feel and have two functions startTest() which runs when test starts and endTest() which runs when test end.

MainPage.java:-
MainPage.java is the first frame that displays  when application starts.This page contains a List of Test to choose form and a Combo Box to choose time for test.

TypingTime.java:-
TypingTime.java is file that has code for running time test starts. It has three function getTestTime() that gives the total time taken for test and getMin() that gives the minutes of test's time left and getSec() that gives the seconds of test's time left.

FileTextPage.java:-
FileTestPage.java is the class that has most of the coding. It adds two JTextArea on the frame in which one contains the text from the file and in other JTextArea user will type that text.
This file has the following functions in coding:
fileInput():-  Load text from file to JTextArea.
underliine():- Gets and the next word to be typed and highlight that word in TextArea.
check():- Checks weather the word user type matches with the word which has to be typed.
backSpace():- Allows user to only correct currently typing word(cannot go beyond the space).
result():- Calculate and Show Result.

Download Files Here:



Monday, August 16, 2010

JAVA : Flickering Problem In Paint Method

Remove Flickering Problem


 Flickering is a big problem while drawing something on screen in Java. Flickering normally occurs when drawing images one after another. Though flickering is a big problem people might think that it could be very complicated to avoid or remove it completely, but it is quite easy to that. By making some simple changes in your code you can completely remove flickering in your animations.
No Flickering                                                     Flickering 


!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!

What causes flickering in Java? 
Before flickering problem can be solved, we should know what causes it? As we know the paint() method in Java first clears the screen and then paints a new frame on the window. So there are two operations takes place when we can the paint() or repaint() method. So some times screen gets updated between the clearing of window and painting of new frame and in that moment of time we can see the cleared window and that makes it appear to be flicker.

Remove Flickering using Double Buffering:
As now we know that the flickering occurs because of refreshing of screen between the clearing of window and painting of new frame, so the solution is to paint the window in such a way that screen doesn't get refreshed before window get completely painted.
This can be done using the Double Buffering. To implement Double Buffering a BufferedImage class. A BufferedImage object is like an Image object except it has some method that makes it easier to work with.

Code in which flickering problem occur

public void run(){
            try{
                Thread.sleep(50);
            }
             catch(Exception e){ }
            repaint();
}
public void paint(Graphics g){
         animation(g);          //this function performs all animation
}


Code for Declaration of Buffered Image object

 
BufferedImage  bf = new BufferedImage( this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);

Code for Remove flickering in paint method by using Buffered Image
public void run(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
            paint(this.getGraphics());
            }
      }
public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
      }

This is how a Buffered Image object is use to prevent the flicker problem. When calling the animation() method a graphics object is extracted form Buffered Image. This Buffered Image graphics object is same as the normal(window) graphics object except this graphics object contains information about the Buffered Image instead of the actual window. That means the animation method paints the new frame on the Buffered Image instead of the actual window. So far the window still holds the old frame and the Buffered Image holds the new frame. Than a call is made to the drawImage() method of graphics object of the window. So now in only one operation the whole content of window is replace by  the content of Buffered Image. This is known as an atomic operation and the screen can not get refreshed while the window is partially painted. This is how the flickering problem can be solved and this code can be use for any type of application.

Now to understand why this code does not use repaint() method we need to understand the repaint() method.

Working of repaint() method:
Some people might think that repaint() method calls to the paint() method, eventually it does but it is not the whole story though. A repaint() method actually calls the update() method and the default update() method then calls to the paint() method. If you Java code did not override update(), the default implementation of update() clears the component's background and simply calls paint().
So if we want to use repaint() method we have to override update() method to avoid flickering.

public void run(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
              repaint();
            }
      }

public void update(Graphics g){
       paint(g);
}

public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
}

Download Files Here: