Monday, 6 June 2011

Merge Sort in java


public class MergeSortArray {
  private long[] theArray;

  private int nElems;

  public MergeSortArray(int max) {
    theArray = new long[max];
    nElems = 0;
  }

  public void insert(long value) {
    theArray[nElems] = value; // insert it
    nElems++; // increment size
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(theArray[j] + " ");
    System.out.println("");
  }

  public void mergeSort() {
    long[] workSpace = new long[nElems];
    recMergeSort(workSpace, 0, nElems - 1);
  }

  private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) {
    if (lowerBound == upperBound) // if range is 1,
      return; // no use sorting
    else { // find midpoint
      int mid = (lowerBound + upperBound) / 2;
      // sort low half
      recMergeSort(workSpace, lowerBound, mid);
      // sort high half
      recMergeSort(workSpace, mid + 1, upperBound);
      // merge them
      merge(workSpace, lowerBound, mid + 1, upperBound);
    }
  }

  private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) {
    int j = 0; // workspace index
    int lowerBound = lowPtr;
    int mid = highPtr - 1;
    int n = upperBound - lowerBound + 1; // # of items

    while (lowPtr <= mid && highPtr <= upperBound)
      if (theArray[lowPtr] < theArray[highPtr])
        workSpace[j++] = theArray[lowPtr++];
      else
        workSpace[j++] = theArray[highPtr++];

    while (lowPtr <= mid)
      workSpace[j++] = theArray[lowPtr++];

    while (highPtr <= upperBound)
      workSpace[j++] = theArray[highPtr++];

    for (j = 0; j < n; j++)
      theArray[lowerBound + j] = workSpace[j];
  }

  public static void main(String[] args) {
    int maxSize = 100; // array size
    MergeSortArray arr = new MergeSortArray(maxSize); // create the array

    arr.insert(14);
    arr.insert(21);
    arr.insert(43);
    arr.insert(50);
    arr.insert(62);
    arr.insert(75);
    arr.insert(14);
    arr.insert(2);
    arr.insert(39);
    arr.insert(5);
    arr.insert(608);
    arr.insert(36);

    arr.display();

    arr.mergeSort();

    arr.display();
  }
}


Bubble Sort in java


public class BubbleSort {
  private long[] a;

  private int nElems;

  public BubbleSort(int max) {
    a = new long[max];
    nElems = 0;
  }

  //   put element into array
  public void insert(long value) {
    a[nElems] = value;
    nElems++;
  }

  //   displays array contents
  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(a[j] + " ");
    System.out.println("");
  }

  public void bubbleSort() {
    int out, in;

    for (out = nElems - 1; out > 1; out--)
      // outer loop (backward)
      for (in = 0; in < out; in++)
        // inner loop (forward)
        if (a[in] > a[in + 1]) // out of order?
          swap(in, in + 1); // swap them
  }

  private void swap(int one, int two) {
    long temp = a[one];
    a[one] = a[two];
    a[two] = temp;
  }

  public static void main(String[] args) {
    int maxSize = 100; // array size
    BubbleSort arr; // reference to array
    arr = new BubbleSort(maxSize);

    arr.insert(77); // insert 10 items
    arr.insert(66);
    arr.insert(44);
    arr.insert(34);
    arr.insert(22);
    arr.insert(88);
    arr.insert(12);
    arr.insert(00);
    arr.insert(55);
    arr.insert(33);

    arr.display();

    arr.bubbleSort();

    arr.display();
  }
}


selection sort in java


   
public class SelectionSort {
  private long[] a;

  private int nElems;

  public SelectionSort(int max) {
    a = new long[max];
    nElems = 0;
  }

  public void insert(long value) {
    a[nElems] = value;
    nElems++;
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(a[j] + " ");
    System.out.println("");
  }

  public void selectionSort() {
    int out, in, min;

    for (out = 0; out < nElems - 1; out++) // outer loop
    {
      min = out; // minimum
      for (in = out + 1; in < nElems; in++)
        // inner loop
        if (a[in] < a[min]) // if min greater,
          min = in; // a new min
      swap(out, min); // swap them
    }
  }

  private void swap(int one, int two) {
    long temp = a[one];
    a[one] = a[two];
    a[two] = temp;
  }

  public static void main(String[] args) {
    int maxSize = 100;
    SelectionSort arr; // reference to array
    arr = new SelectionSort(maxSize); // create the array

    arr.insert(17); // insert 10 items
    arr.insert(29);
    arr.insert(34);
    arr.insert(45);
    arr.insert(52);
    arr.insert(68);
    arr.insert(71);
    arr.insert(80);
    arr.insert(96);
    arr.insert(33);

    arr.display();

    arr.selectionSort();

    arr.display();
  }

}


string sorting in java


import java.util.Arrays;

public class StringSorting {
  public static void main(String[] args) {
    String[] sa = new String[] { "d", "e", "a", "c", "g" };

    System.out.println("Before sorting: " + Arrays.asList(sa));
    Arrays.sort(sa);
    System.out.println("After sorting: " + Arrays.asList(sa));
  }
}

Simple sort using java


public class SortDemo {
    public static void main(String[] args) {
        int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
                              2000, 8, 622, 127 };

        for (int i = arrayOfInts.length; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (arrayOfInts[j] > arrayOfInts[j+1]) {
                    int temp = arrayOfInts[j];
                    arrayOfInts[j] = arrayOfInts[j+1];
                    arrayOfInts[j+1] = temp;
                }
            }
        }

        for (int i = 0; i < arrayOfInts.length; i++) {
            System.out.print(arrayOfInts[i] + " ");
        }
        System.out.println();
    }
}


queue implementation in java


import java.io.*;
import java.util.*;

public class QueueImplement{
LinkedList<Integer> list;
String str;
int num;
public static void main(String[] args){
QueueImplement q = new QueueImplement();
}
public QueueImplement(){
try{
list = new LinkedList<Integer>();
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.println("Enter number of elements : ");
str = bf.readLine();
if((num = Integer.parseInt(str)) == 0){
System.out.println("You have entered either zero/null.");
System.exit(0);
}
else{
System.out.println("Enter elements : ");
for(int i = 0; i < num; i++){
str = bf.readLine();
int n = Integer.parseInt(str);
list.add(n);
}
}
System.out.println("First element :" + list.removeFirst());
System.out.println("Last element :" + list.removeLast());
System.out.println("Rest elements in the list :");
while(!list.isEmpty()){
System.out.print(list.remove() + "\t");
}
}
catch(IOException e){
System.out.println(e.getMessage() + " is not a legal entry.");
System.exit(0);
}
}
}



stack demo in java


import java.util.*;

public class StackDemo{
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(new Integer(10));
stack.push("a");
System.out.println("The contents of Stack is" + stack);
System.out.println("The size of an Stack is" + stack.size());
System.out.println("The number poped out is" + stack.pop());
System.out.println("The number poped out is " + stack.pop());
//System.out.println("The number poped out is" + stack.pop());
System.out.println("The contents of stack is" + stack);
System.out.println("The size of an stack is" + stack.size());
}
}



display month calendar in java


import java.util.*;
import java.text.*;

public class MonthCalender {

public final static String[] monthcalender = {
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};

public final static int daysinmonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

private void displayMonth(int month, int year) {

// The number of days to leave blank at
// the start of this month.

int blankdays = 0;
System.out.println("  " + monthcalender[month] + " " + year);

if (month < 0 || month > 11) {
throw new IllegalArgumentException(
"Month " + month + " is not valid and must lie in between 0 and 11");
}

GregorianCalendar cldr = new GregorianCalendar(year, month, 1);
System.out.println("Sunday Monday Tuesday Wednesday Thursday Friday Saturday");

// Compute how much to leave before before the first day of the month.
// getDay() returns 0 for Sunday.

blankdays = cldr.get(Calendar.DAY_OF_WEEK)-1;
int daysInMonth = daysinmonths[month];

if (cldr.isLeapYear(cldr.get(Calendar.YEAR)) && month == 1) {

++daysInMonth;
}

// Blank out the labels before 1st day of the month
for (int i = 0; i < blankdays; i++) {
System.out.print("   ");
}

for (int i = 1; i <= daysInMonth; i++) {

// This "if" statement is simpler than messing with NumberFormat
if (i<=9) {
System.out.print(" ");
}
System.out.print(i);

if ((blankdays + i) % 7 == 0) { // Wrap if EOL
System.out.println();
}
else {
System.out.print(" ");
}
}
}

/**
     * Sole entry point to the class and application.
     * @param args Array of String arguments.
     */
    public static void main(String[] args) {

int mon, yr;
MonthCalender moncldr = new MonthCalender();

if (args.length == 2) {
moncldr.displayMonth(Integer.parseInt(args[0])-1, Integer.parseInt(args[1]));
}
else {
Calendar todaycldr = Calendar.getInstance();
moncldr.displayMonth(todaycldr.get(Calendar.MONTH), todaycldr.get(Calendar.YEAR));
}
}
}