Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, June 6, 2021

Reading in delimited line from text file in Java

 I have a text file in which I have stored some text data which describes the areas of Colombo which is also known as the Commercial capital of Sri Lanka. I need to read the data from a text file and display on screen with a different format.

There are many ways to reach this target. Here I have used BufferedReader to read the file line by line using a FileReader.

My project structure is as below.









Below is the text file (Colombo.txt)









So, here is the solution

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("Colombo.txt"));
try{
String num;
String englishName;
String nativeName;
String readLine = br.readLine();
while (readLine != null){
num = readLine.split(",")[0];
englishName = readLine.split(",")[1];
nativeName = readLine.split(",")[2];

System.out.println("Colombo " + num + " - " + englishName + " - " + nativeName );
readLine = br.readLine();
}
}finally {
if(br != null){
br.close();
}
}
}
}

Let me explain the concept behind the try-with-resources statement in Java which is introduced in Java 7

The try-with-resources statement is a try statement that declares one or more resources .

A resource is an object that must be closed after the program is finished with it.

This statement ensures that each resource is closed at the end of the statement.

Coming back to our example, let me put the above challenge in a much cleaner way using try-with-resources statement instead of a try statement. 

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
public static void main(String[] args) throws IOException{
try(BufferedReader br = new BufferedReader(new FileReader("Colombo.txt"))){
String num;
String englishName;
String nativeName;
String readLine = br.readLine();
while (readLine != null){
num = readLine.split(",")[0];
englishName = readLine.split(",")[1];
nativeName = readLine.split(",")[2];

System.out.println("Colombo " + num + " - " + englishName + " - " + nativeName );
readLine = br.readLine();
}
}
}
}

As you can see, I have declared the BufferedReader as a resource which doesn't need to be closed at the finally block explicitly. This reduces several lines of code and makes the code simpler.

Output


I hope it was useful...

download code

Sunday, December 13, 2020

Print name of each digit of a number in Java

 Challenge is to write a method to print the passed number using words for each of the digits. If the number is negative then print "Invalid Value". 

I simply used the String manipulations in Java to resolve this issue with aid of a Switch statement to identify each digit and get the corresponding name of the digit.

Below is my working solution and I hope it is helpful.

public class NumberToWords {
public static void numberToWords(int number){
String resultString = "";
if(number < 0){
resultString = "Invalid Value";
}else{
String numberString = String.valueOf(number);

for(int i=0; i<numberString.length(); i++){
int currentNumber = Character.getNumericValue
(numberString.charAt(i));

resultString = resultString +
getNameOfNumber(currentNumber) + " ";
}
}
System.out.println(resultString);
}

public static String getNameOfNumber(int num){
String numberName = "";
switch (num){
case 0 :
numberName = "Zero";
break;
case 1:
numberName = "One";
break;
case 2:
numberName = "Two";
break;
case 3:
numberName = "Three";
break;
case 4:
numberName = "Four";
break;
case 5:
numberName = "Five";
break;
case 6:
numberName = "Six";
break;
case 7:
numberName = "Seven";
break;
case 8:
numberName = "Eight";
break;
case 9:
numberName = "Nine";
break;
default:
numberName = "Invalid";
break;
}
return numberName;
}
}



How to find the greatest common divisor of two integers in java?

This was another coding challenge I came across while practising online. Little bit tricky, however, I found a solution (I say 'a' solution because there can be alternative ways to do the same) for it. 

So, what are we suppose to do here?

  • A method accepts two integer parameters and we need to find the highest divisible integer by which both the numbers could be divided without a remainder.
  • If either one of the given number is less than 10 then the method should return -10 indicating invalid input.
here is my solution and I hope it's helpful.

public class GreatestCommonDivisor {
public static int getGreatestCommonDivisor(int first, int second){
int greatestCommonDivisor = -1;

if(first >= 10 && second >= 10){
int smallerNumber = first < second ? first : second;

for(int i = smallerNumber ; i >= 1 ; i--){
if( (first % i == 0) && (second % i == 0)){
greatestCommonDivisor = i;
break;
}else{
continue;
}
}
}
return greatestCommonDivisor;
}
}

Java program to get only the even digit sum of a given integer

 Yet another coding challenge I came across and here is the challenge ; 

you are given an Integer number

return - 1 if it is a negative number

if not, calculate the sum of all the even digits of the given number

    e.g:- 1658 is given then sum = 6 + 8 which is 14

below is my solution and I hope it helps

public class EvenDigitSum {
public static int getEvenDigitSum(int number){
int sumOfEvenDigits = 0;

if(number < 0){
sumOfEvenDigits = -1;
}else{
int lengthOfNumber = String.valueOf(number).length();

for(int i=0 ; i< lengthOfNumber ; i++){
int currentNumber = Character.getNumericValue(String.valueOf(number).charAt(i));
if(currentNumber % 2 == 0){
sumOfEvenDigits += currentNumber;
}else{
continue;
}
}
}
return sumOfEvenDigits;
}
}


How to check a given number is a palindrome in Java ?

This is another online coding challenge I came across recently to which I found a simple solution with the use of String and StringBuffer in java. 

Let me explain the challenge here,

  • A given number is a palindrome when reversed is equal to the original number (e.g : 121, 45654,1001)
  • If the given number is a palindrome, then return true else return false
In my solution I basically convert the integer number to a string in order to reverse the number, Unfortunately java doesn't have a reverse method in String class (it's java 11 that I'm working with). However, StringBuilder has a reverse method to which a String needs to be parsed. So, here's what I'm doing.

get the Integer number --> convert to String --> convert to StringBuilder --> reverse the string --> convert back to String --> convert the string back to number --> store it in a new int variable --> compare with the original number --> return true if matches or return false unless otherwise

why do I use Math.abs() ?

This is simply to handle any negative numbers. for an instance, -232 is a palindrome but if we straight away convert it to string this will reverse the string as 232- which ends up with an invalid integer. To handle this, I have considered the absolute value by using Math.abs() function to only get the absolute value of the given number.

find my solution as below

public class NumberPalindrome {
public static boolean isPalindrome(int number){
boolean result = false;
number = Math.abs(number);
int reversedNumber = Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString());

if(number == reversedNumber){
result = true;
}
return result;
}
}

Simple Java program to calculate the sum of all the digits of a number

 I just came across a simple yet an interesting challenge when I was attempting some online coding practices and thought to share it with you. Firstly would like to state that there can be many ways to separate each digit of the given number but I have used the most convenient way by converting it to String and processing.

Let me explain you the challenge.

  • An integer number is given and it should be at least a two digit number (15, 896 etc but not 9). Return -1 if this is not met.
  • If the above condition is met, then sum up all the digits of the number and return.
find my solution as below

public class DigitSum {
public static int sumDigits(int number){
int sum = 0;
if(number >= 10){
int numOfDigits = String.valueOf(number).length();

for(int i=0; i<numOfDigits ; i++){
sum += Character.getNumericValue(String.valueOf(number).charAt(i));
}
}else{
sum = -1;
}
return sum;
}
}

Thursday, December 3, 2020

How to validate a username with the aid of regular expressions in Java?

 I find regular expressions interesting because if you got the right idea of when and how to use them, it will help you to reduce lines of code and would save time as well. 

In the below example, I am going to demonstrate on how to validate a simple username (assume username entered in a System during the Sign Up process) .

Rules

  • The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
  • The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a-z] uppercase character [A - Z], and digits [0 - 9].
  • The first character of the username must be an alphabetic character, i.e., either lowercase character [a - z] or uppercase character [A -Z]

I am going to use the stdin to get inputs and stdout to print the results. The first input will indicate how many input strings (usernames) are going to be validated and subsequent inputs will indicate each username to be validated.

import java.util.Scanner;

class Validator {
public static final String regularExpression = "^[a-zA-Z][a-zA-Z0-9|_]{7,29}$";
}

public class UsernameValidator{
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int numOfUserNames = Integer.parseInt(scanner.nextLine());

while(numOfUserNames > 0){

String userName = scanner.nextLine();

if(userName.matches(Validator.regularExpression)){
System.out.println("Valid Username");
}else{
System.out.println("Invalid Username");
}
numOfUserNames--;
}
}
}

Input / Output:


5
Amanda
Invalid Username
Cassandra
Valid Username
Amelia_2134
Valid Username
1Jessica231
Invalid Username
Emma_654424
Valid Username

Explanation to the regular expression I used above

^ [a-zA-Z] --> indicates the beginning of the string which should contain a-z or A-Z (only alphabets)
[a-zA-Z-0-9_] --> indicates the string starting from the second character of the username which can consists of alphabets, digits or _. No Symbols allowed here. 
{7,29}  --> indicates the length of the username starting from the second character. which is 7 to 29 character long.

A great approach to practice regular expressions is to create your own simple java programs and imagine various types of validations that could perform in a System, and crack them with the aid of Regular expressions instead of using String manipulations or conditional blocks to resolve the challenges.




Sunday, November 29, 2020

How to check two strings have a common substring in Java?

Given two strings, determine if they share a common substring. A substring may be as small as one character.

For example, the words "j", "and", "jug" share the common substring 'j' The words "or" and "fit" do not share a substring.

Input Format

The first line contains a single integer , the number of test cases.

The following  pairs of lines are as follows:

  • The first line contains string s1
  • The second line contains string s2

Output Format

For each pair of strings, return YES or NO.

Sample Input

2

she

saw

dress

pat

Sample Output

YES

NO

There is a basic approach for this challenge which by using a nested for loop we can detect common substrings (outer for loop traverse through s1 and the inner for loop traverse through s2. For each character in s1, each character of s2 will be matched and if same character is found , return YES and break) , however this solution is not efficient because its complexity is O(n^2).

Below approach is more efficient in which I store each character of the s1 string in a Set and then traverse through s2 String to find whether the above set contains any of the character of s2. 

Find my solution below.

static String twoStrings(String s1, String s2) {
String result="NO";
Set<Character> set1 = new HashSet<Character>();

for (char s : s1.toCharArray()){
set1.add(s);
}

for(int i=0;i<s2.length();i++){
if(set1.contains(s2.charAt(i))){
result = "YES";
break;
}
}
return result;
}




Finding whether a given string has balanced parenthesis using Java Stack

 Challenge: Given a string in the stdin with a set of parenthesis [{[()]}] and the stdout should print either true or false based on whether the parenthesis are matched or not

e.g: 

{} --> true

{[()]} -->true

{[}] -- > false

Solution : I am going to use a Java Stack to resolve this problem following the below approach.

1.use stdin to read the input

2.iterate reading from stdin while there are more inputs

3.store each string in a variable and validate

4.validation >> 

    a. loop through each character of the string

    b.If current character is ( OR { OR [ then add the value to the Stack

    c.If the current character is ) OR } OR ] then pop a value from the Stack and compare it with the current character

   d. if matches then result is true , continue ; else set result as false 

Below is the coding

-----------------------------------------------------------------------------------------------------------------------------

package com.hackerrank;

import java.util.Scanner;
import java.util.Stack;

public class Main {

/**
* Main method
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //stdin
while(scanner.hasNext()){ //reading continues till stdin has more inputs
String input = scanner.nextLine(); //read String
System.out.println(checkBalancedLine(input)); //validate and print result
}
}

/**
* This method validates the string with balanced paranthesis
* @param inputLine
* @return true or false
*/
public static boolean checkBalancedLine(String inputLine){
boolean balanced =false;

Stack<String> stringStack = new Stack<String>();

for(int i=0;i<inputLine.length();i++){
if((inputLine.charAt(i)=='(') || (inputLine.charAt(i)=='{') || (inputLine.charAt(i)=='[')) { //if the character is ([{ then add to the stack
stringStack.add(String.valueOf(inputLine.charAt(i)));
}
if((inputLine.charAt(i)==')') || (inputLine.charAt(i)=='}') || (inputLine.charAt(i)==']')) { //if the character is )]} then pop the stack and compare the ith value against the popped value
if(!stringStack.isEmpty()) {
String poppedString = stringStack.pop();
if (inputLine.charAt(i) == ')' && poppedString.equalsIgnoreCase("(")) {
balanced = true;
} else if (inputLine.charAt(i) == ']' && poppedString.equalsIgnoreCase("[")) {
balanced = true;
} else if (inputLine.charAt(i) == '}' && poppedString.equalsIgnoreCase("{")) {
balanced = true;
} else {
balanced = false;
}
}
}
}
return balanced;
}
}

   Console 


Thursday, April 28, 2016

How to set the Windows look and feel for a Swing application

In this post I am going to show you how to change the default look and feel of a Swing application to a Windows look.

Before











After











Below is the sample code


   /*  
   * This method sets the current System's look and feel for the GUI  
   *  
   * */  
   public void setLookAndFeel(){  
     try {  
       // Set System Look and Feel  
       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  
     }  
     catch (UnsupportedLookAndFeelException e) {  
       errorString = e.getMessage();  
       e.printStackTrace();  
     }  
     catch (ClassNotFoundException e) {  
       errorString = e.getMessage();  
       e.printStackTrace();  
     }  
     catch (InstantiationException e) {  
       errorString = e.getMessage();  
       e.printStackTrace();  
     }  
     catch (IllegalAccessException e) {  
       errorString = e.getMessage();  
       e.printStackTrace();  
     }  
   }  


Hope it was useful to you.

Wednesday, April 27, 2016

Creating a Toolbar in Swing

In my earlier post I described how to add a JMenuBar with menu items and sub menu items. I am going to show how to add a tool bar to the same application under the menu bar as shown below.













I have highlighted the code to add the tool bar to the same JFrame.

 import javax.swing.*;  
 import java.awt.*;  
 public class ToolBarExampleMain extends JFrame{  
   public ToolBarExampleMain(){  
     super("Tool Bar Example App");           //sets the title for the JFrame  
     this.createInterface();  
   }  
   public void createInterface(){  
     setLayout(new BorderLayout());           //main Layout of the JFrame is BorderLayout  
     Toolkit tk = Toolkit.getDefaultToolkit();  
     int xSize = ((int) tk.getScreenSize().getWidth());  
     int ySize = ((int) tk.getScreenSize().getHeight());  
     setSize(xSize,ySize);                //setting the JFrame size according to the screen width and height  
     JPanel mainPanel = new JPanel(new BorderLayout());  
     mainPanel.add(createMenuBar(),BorderLayout.NORTH); //creating a JMenuBar and adding it on top of the frame  
     mainPanel.add(createToolBar(),BorderLayout.LINE_START);  
     add(mainPanel, BorderLayout.CENTER);  
     setVisible(true);  
   }  
   public JMenuBar createMenuBar(){  
     JMenuBar menuBar=new JMenuBar();  
     JMenu menuFile=new JMenu("File");          //File,Edit,View and Help are the main menus in the JMenuBar  
     JMenu menuEdit=new JMenu("Edit");  
     JMenu menuView=new JMenu("View");  
     JMenu menuHelp=new JMenu("Help");  
     JMenuItem subMenuItemOpen=new JMenuItem("Open");  //Open and Exit are the sub menu items under 'File' menu item  
     JMenuItem subMenuItemExit=new JMenuItem("Exit");  
     menuFile.add(subMenuItemOpen);  
     menuFile.add(subMenuItemExit);  
     menuBar.add(menuFile);  
     menuBar.add(menuEdit);  
     menuBar.add(menuView);  
     menuBar.add(menuHelp);  
     return menuBar;  
   }  
   public static void main(String[] args){  
     ToolBarExampleMain main=new ToolBarExampleMain();  
   }  
   public JPanel createToolBar(){  
     JToolBar toolBar=new JToolBar();  
     toolBar.setRollover(true);  
     //buttons required for the tool bar  
     JButton btnMoveUp;  
     JButton btnMoveDown;  
     JButton btnAdd;  
     JButton btnRemove;  
     JButton btnComment;  
     JButton btnMessageBox;  
     //icon which sets an image to each of the butons in the tool bar  
     Icon btnIcon;  
     //this JPanel will hold the tool bar  
     JPanel toolBarPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));  
     //Designing the Up Arrow button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\upArrow.png"));  
     btnMoveUp=new JButton(btnIcon);  
     //setting a tool tip for the button  
     btnMoveUp.setToolTipText("Move up ");  
     //adding the button to the toolbar  
     toolBar.add(btnMoveUp);  
     //adding a separator after the button  
     toolBar.addSeparator();  
     //Designing the Down Arrow button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\downArrow.png"));  
     btnMoveDown=new JButton(btnIcon);  
     btnMoveDown.setToolTipText("Move Down");  
     toolBar.add(btnMoveDown);  
     toolBar.addSeparator();  
     //Designing the Add button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\add.png"));  
     btnAdd=new JButton(btnIcon);  
     btnAdd.setToolTipText("Add new Test Case");  
     toolBar.add(btnAdd);  
     toolBar.addSeparator();  
     //Designing the Remove button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\remove.png"));  
     btnRemove=new JButton(btnIcon);  
     btnRemove.setToolTipText("Remove");  
     toolBar.add(btnRemove);  
     toolBar.addSeparator();  
     //Designing the Comment button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\comment.png"));  
     btnComment=new JButton(btnIcon);  
     btnComment.setToolTipText("Comment");  
     toolBar.add(btnComment);  
     toolBar.addSeparator();  
     //Designing the Message Box button  
     btnIcon=new ImageIcon(getClass().getResource("\\icons\\messageBox.png"));  
     btnMessageBox=new JButton(btnIcon);  
     btnMessageBox.setToolTipText("Message Box");  
     toolBar.add(btnMessageBox);  
     toolBar.addSeparator();  
     toolBarPanel.add(toolBar);  
     return toolBarPanel;  
   }  
 }  
Note that you can add action listeners to the buttons in the tool bar as same as you do to JButtons.

Hope it helped you.

Adding a JFileChooser when clicking on a JMenuItem

In my previous post I showed how to add a JMenuBar to a Swing JFrame. In this post I will show you how to display a file chooser when clicking one of the items in the menu bar as below.

In this app, when the user selects the 'Open' menu tem from the menu bar then it will allow you to browse a location in your machine to select a file. Once you click on 'Exit' then the program exits.


















According to a code below, if the user selects a file or cancels the file selection, a message box will popup accordingly. You can perform any action in the appropriate code blocks as required.

 import javax.swing.*;  
 import java.awt.*;  
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import java.io.File;  
 public class MenuBarExampleMain extends JFrame implements ActionListener{  
   private static String OPEN_COMMAND="open";  
   private static String EXIT_APP_COMMAND="exit";  
   public MenuBarExampleMain(){  
     super("Menu Bar Example App");           //sets the title for the JFrame  
     this.createInterface();  
   }  
   public void createInterface(){  
     setLayout(new BorderLayout());           //main Layout of the JFrame is BorderLayout  
     Toolkit tk = Toolkit.getDefaultToolkit();  
     int xSize = ((int) tk.getScreenSize().getWidth());  
     int ySize = ((int) tk.getScreenSize().getHeight());  
     setSize(xSize,ySize);                //setting the JFrame size according to the screen width and height  
     JPanel mainPanel = new JPanel(new BorderLayout());  
     mainPanel.add(createMenuBar(),BorderLayout.NORTH); //creating a JMenuBar and adding it on top of the frame  
     add(mainPanel, BorderLayout.CENTER);  
     setVisible(true);  
   }  
   public JMenuBar createMenuBar(){  
     JMenuBar menuBar=new JMenuBar();  
     JMenu menuFile=new JMenu("File");          //File,Edit,View and Help are the main menus in the JMenuBar  
     JMenu menuEdit=new JMenu("Edit");  
     JMenu menuView=new JMenu("View");  
     JMenu menuHelp=new JMenu("Help");  
     JMenuItem subMenuItemOpen=new JMenuItem("Open");  //Open and Exit are the sub menu items under 'File' menu item  
     subMenuItemOpen.setActionCommand(OPEN_COMMAND);  
     subMenuItemOpen.addActionListener(this);  
     JMenuItem subMenuItemExit=new JMenuItem("Exit");  
     subMenuItemExit.setActionCommand(EXIT_APP_COMMAND);  
     subMenuItemExit.addActionListener(this);  
     menuFile.add(subMenuItemOpen);  
     menuFile.add(subMenuItemExit);  
     menuBar.add(menuFile);  
     menuBar.add(menuEdit);  
     menuBar.add(menuView);  
     menuBar.add(menuHelp);  
     return menuBar;  
   }  
   public static void main(String[] args){  
     MenuBarExampleMain main=new MenuBarExampleMain();  
   }  
   @Override  
   public void actionPerformed(ActionEvent e) {  
     String command = e.getActionCommand();  
     if (OPEN_COMMAND.equals(command)) {  
       browseFiles();  
     }else if (EXIT_APP_COMMAND.equals(command)) {  
       exitProgram();  
     }  
   }  
   //opens a JFileChooser to browse XML files to parse to the application  
   public void browseFiles(){  
     final JFileChooser fileChooser = new JFileChooser();  
     //allows user to select more than one file  
     fileChooser.setMultiSelectionEnabled(true);  
     int returnVal = fileChooser.showOpenDialog(null);  
     String fileExtension;  
     //if the user confirms file selection display a message  
     if (returnVal == JFileChooser.APPROVE_OPTION) {  
       JOptionPane.showMessageDialog(null, "User made the selection");  
     }  
     else{  
       JOptionPane.showMessageDialog(null, "User canceled the selection");  
     }  
   }  
   public void exitProgram(){  
     System.exit(0);  
   }  
 }  

Adding a Menu with sub menus in Swing

In this blog post I am going to show you how to add the below JMenuBar to a JFrame in a Swing application.









Below is the commented code for the application. I will explain how to add ActionListeners to these menu items once clicked in another post separately.

 import javax.swing.*;  
 import java.awt.*;  
 public class MenuBarExampleMain extends JFrame{  
   public MenuBarExampleMain(){  
  //sets the title for the JFrame  
     super("Menu Bar Example App");             
     this.createInterface();  
   }  
   public void createInterface(){  
  //main Layout of the JFrame is BorderLayout  
     setLayout(new BorderLayout());             
     Toolkit tk = Toolkit.getDefaultToolkit();  
     int xSize = ((int) tk.getScreenSize().getWidth());  
     int ySize = ((int) tk.getScreenSize().getHeight());  
  //setting the JFrame size according to the screen width and height  
     setSize(xSize,ySize);                  
     JPanel mainPanel = new JPanel(new BorderLayout());  
  //creating a JMenuBar and adding it on top of the frame  
     mainPanel.add(createMenuBar(),BorderLayout.NORTH);   
     add(mainPanel, BorderLayout.CENTER);  
     setVisible(true);  
   }  
   public JMenuBar createMenuBar(){  
     JMenuBar menuBar=new JMenuBar();  
  //File,Edit,View and Help are the main menus in the JMenuBar  
     JMenu menuFile=new JMenu("File");            
     JMenu menuEdit=new JMenu("Edit");  
     JMenu menuView=new JMenu("View");  
     JMenu menuHelp=new JMenu("Help");  
  //Open and Exit are the sub menu items under 'File' menu item  
     JMenuItem subMenuItemOpen=new JMenuItem("Open");    
     JMenuItem subMenuItemExit=new JMenuItem("Exit");  
     menuFile.add(subMenuItemOpen);  
     menuFile.add(subMenuItemExit);  
     menuBar.add(menuFile);  
     menuBar.add(menuEdit);  
     menuBar.add(menuView);  
     menuBar.add(menuHelp);  
     return menuBar;  
   }  
   public static void main(String[] args){  
     MenuBarExampleMain main=new MenuBarExampleMain();  
   }  
 }  

Thursday, January 10, 2013

A simulator for sorting algorithms

I have worked on simulating sorting process of two sorting algorithms. They are bubble sort and selection sort. Let me explain them a bit before giving you the resources.

Selection Sort

In computer science, a selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) time complexity, making it inefficient on large lists. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The idea of algorithm is quite simple. Array is imaginary divided into two parts - sorted one and unsorted one. At the beginning, sorted part is empty, while unsorted one contains whole array. At every step, algorithm finds minimal element in the unsorted part and adds it to the end of the sorted one. When unsorted part becomes empty, algorithm stops.

When algorithm sorts an array, it swaps first element of unsorted part with minimal element and then it is included to the sorted part. This implementation of selection sort in not stable. In case of linked list is sorted, and, instead of swaps, minimal element is linked to the unsorted part, selection sort is stable.

Let us see an example of sorting an array to make the idea of selection sort clearer.

array unsorted = {5,23,34,87,56,42}

array unsorted = {5,23,34,42,56,87}

Bubble Sort

bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" Javato the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

steps
  1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
  2. If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.


I have simulated this process to show the steps one by one using a java applet. the code is fully commented, so it would be easy for you to understand.

download the source code from here