Showing posts with label Shell Sort. Show all posts
Showing posts with label Shell Sort. Show all posts

Wednesday, August 17, 2016

Shell Sort Algorithm implementation in java


Shell sort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort).The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements, it can move some out-of-place elements into position faster than a simple nearest neighbor exchange.
The running time of Shell sort is heavily dependent on the gap sequence it uses.

Pseudocode: 

# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]

# Start with the largest gap and work down to a gap of 1
[[foreach]] (gap in gaps)
{
    # Do a gapped insertion sort for this gap size.
    # The first gap elements a[0..gap-1] are already in gapped order
    # keep adding one more element until the entire array is gap sorted
    for (i = gap; i < n; i += 1)
    {
        # add a[i] to the elements that have been gap sorted
        # save a[i] in temp and make a hole at position i
        temp = a[i]
        # shift earlier gap-sorted elements up until the correct location for a[i] is found
        for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
        {
            a[j] = a[j - gap]
        }
        # put temp (the original a[i]) in its correct location
        a[j] = temp
    }
}

So,Shell Sort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sub-lists of every h’th element is sorted.

Time Complexity:

 Time complexity of above implementation of shell-sort is O(n2). In the above implementation gap is reduce by half in every iteration. There are many other ways to reduce gap which lead to better time complexity.


Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ShellSortApp
{
static void printArray(int arr[])
       {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    /* function to sort arr using shellSort */
    int sort(int arr[])
    {
        int n = arr.length;

        // Start with a big gap, then reduce the gap
        for (int gap = n/2; gap > 0; gap /= 2)
        {
            for (int i = gap; i < n; i += 1)
            {
                int temp = arr[i];
                int j;
                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                    arr[j] = arr[j - gap];

                arr[j] = temp;
            }
        }
        return 0;
    }

public static void main(String[] args)
{
int arr[] = {12, 34, 54, 2, 3};
       System.out.println("Array before sorting");
       printArray(arr);

       ShellSortApp ob = new ShellSortApp();
       ob.sort(arr);

       System.out.println("Array after sorting");
       printArray(arr);
}

}

Result: 

Array before sorting
12 34 54 2 3 
Array after sorting
2 3 12 34 54 

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();
}


}