Monday, June 13, 2016

Shell Sort example in java

Shell sort is a sorting algorithm that requires asymptotically fewer than O(n²) comparisons and exchanges in the worst case. Although it is easy to develop an intuitive sense of how this algorithm works, it is very difficult to analyze its execution time, but estimates range from O(nlog2 n) to O(n1.5) depending on implementation details.

Shell sort is a generalization of insertion sort, with two observations in mind:

Insertion sort is efficient if the input is "almost sorted".
Insertion sort is inefficient, on average, because it moves values just one position at a time.
Shell sort improves insertion sort by comparing elements separated by a gap of several positions. This lets an element take "bigger steps" toward its expected position. Multiple passes over the data are taken with smaller and smaller gap sizes. The last step of Shell sort is a plain insertion sort, but by then, the array of data is guaranteed to be almost sorted.

Consider a small value that is initially stored in the wrong end of the array. Using an O(n²) sort such as bubble sort or insertion sort, it will take roughly n comparisons and exchanges to move this value all the way to the other end of the array. Shell sort first moves values using giant step sizes, so a small value will move a long way towards its final position, with just a few comparisons and exchanges.

Code example:

/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

class ArraySh
{
 private long[] theArray;
 private int nElems;

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

 public void insert(long values)
 {
theArray[nElems] =values;
nElems++;
 }

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

 public void shellSort()
 {
int inner,outer;
long temp;
int h=1;

while(h<=nElems/3)
h=h*3 +1;
while(h>0)
{
for(outer =h;outer<nElems;outer++)
{
temp=theArray[outer];
inner=outer;

while (inner > h-1 && theArray[inner-h] >=temp)
{
theArray[inner] =theArray[inner -h];
inner-=h;
}
theArray[inner]=temp;
}
h=(h-1)/3;

}
 }

}
public class ShellSortApp
{


public static void main(String[] args)
{
ArraySh arr=new ArraySh(10);
for(int j=0;j<10;j++)
{
long n=(int)(java.lang.Math.random()*99);
arr.insert(n);

}
arr.display();
arr.shellSort();
arr.display();
}


}

No comments: