Wednesday, August 27, 2008

Implementation of quicksort in java

Hello ~Friends~

Yesterday I was going through a wonderful lecture series on quick sort, check it out at Erik Demaine.
I found it very enchanting thought provoking. Although I did not understand all the Maths, but I think I understood most of it.
So here goes my implementation of quick sort in Java. Here's the program and explanation.

Explanation:
Quick sort is a sorting algorithm belonging to the divide and conquer family of algorithms. What this means is that recursion is used as a primary implementation technique.
Advantages of the quick sort algorithm.
1> Very fast, almost 3 times faster than insertion sort.
2> Very easy and intuitive implementation.

So here's how we do it:
1> We pick any element at random and swap it with the first element of the array.
2> The first element is made a pivot element and compared and swapped to all elements in the array, such that all elements to the left of pivot are <>pivot.
3> The 2 such sub-array are again portioned and sorted according to statement 1.

Here's the code.

package sorting;



public class QuickSortArray {

public void printArray(int[] array)
{
for(int i: array)
System.out.println(i);
}

public void quickSort(int[] array, int p, int q)
{
//The recursion break condition is when p > q.
if(p < q)
{
int r=partition(array, p, q);
quickSort(array, p, r-1);
quickSort(array, r+1, q);
}

}

public int partition(int[] array, int p, int q)
{
//I need to explain the first statement,
//What Prof Erik states in his lecture is that
//the worst runtimes for this algo are seen in case
//the array is already sorted.
//To guard against this posibility, we randomly swap the
//first element of the array with a random location within the
//sub-array. Please check http://www.catonmat.net/blog/mit-introduction-to-algorithms-part-three/
//for more details.

int number=(int)(p+(Math.random()*(q-p)));
swap(array, p, number);
//We firstly make the first element a pivot.
int pivot=array[p];
int i=p;

for(int j=p+1; j<=q; j++)
{
//When ever the value of a[j] < pivot we swap the value with i.
if(array[j] < pivot)
{

swap(array, ++i, j);
}

}
swap(array, p, i );

return i;
}

public void genrateRandom()
{
int number=(int)(Math.random()*10.0);
System.out.println(number);
}

public void swap(int[] array,int p, int q)
{
int temp;
temp=array[p];
array[p]=array[q];
array[q]=temp;
}


public static void main(String[] args) {
int array[]={20,2,7,34,1,10,15,35,62,12,45};

//(array, 0, number);
QuickSortArray swap=new QuickSortArray();
//int number=(int)(Math.random()*10.0);
//swap.swap(array, 0, number);
swap.printArray(array);
swap.quickSort(array, 0, 10);
System.out.println("After Sorting");
swap.printArray(array);


}

}

Tuesday, August 26, 2008

Find the number of days since a file was modified.

Many of us have come across a situation where progrmatically we are called upon to delete certain files meeting certain conditions for example: delete all files in the folder that are older than 40 days.
This is how you may solve this problem:
assumption: The base directory where the files are located is: /root/vivek/logs

let us write a simple class that does this:

Here are the steps:
1> Read the directory for files.
2> Find the last modified date for the file.
3> negete it with todays date which gives us the number of days since the file is modiefied.
4> if the number of days > 40 we delete the file.



package testing;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DeleteOldFiles {
//The file object from which we get directory listing of all files.
private File file=null;
public DeleteOldFiles(String directoryPath)
{
file=new File(directoryPath);
}

public List getFileList()
{
ArrayList files=new ArrayList();
String[] dirListing=file.list();
String path=file.getPath();
for(String entity: dirListing)
{
File tmp=null;
tmp=new File(path+"/"+entity);
if(tmp.isFile())
{

//new StringBuffer().append(path).append("/").append(entity).toString()
files.add(tmp.getPath());
}
}

return files;

}

public void deleteFilesWhichAreOld()
{
List fileList=getFileList();
Calendar todaysDate=Calendar.getInstance();
long todaysDateInMilliSec=todaysDate.getTimeInMillis();

for(String file: fileList)
{
File tmp=new File(file);
long lastModifiedDateInMilli=tmp.lastModified();

long diff=todaysDateInMilliSec-lastModifiedDateInMilli;
//The total number of milli secs in a day is 1000 (1 sec=1000 milli sec)
//1000*60(sec)*60(mins)*24(hours)
long days=diff/(1000*60*60*24);

if(days>=40)
{
boolean success;
success=tmp.delete();
if (!success)
throw new IllegalArgumentException();
}


}

}

public static void main(String[] args) {

DeleteOldFiles deFiles=new DeleteOldFiles("/temp");
deFiles.deleteFilesWhichAreOld();
}

}