Categories
Algorithm Algorithms & Design Sort

Shell Sort


public class ShellSort {

	public static void main(String[] args) {
		 int arr[] = {12, 34, 54, 2, 3,16,18,1};

		 System.out.println("printing the array..");
		 printArray(arr);
		 
		 int size = arr.length;
		 shellSort(arr,size);
		
		 
		 System.out.println("printing the sorted array..");
		 printArray(arr);
		 
		 
		 
	}

	public static void shellSort(int arr[], int size){
		
		for(int i=size/2;i>0;i/=2){
			
			for(int j=i;j<size;j++){
				int temp = arr[j];
				for(int k=j;k>=i && arr[k-i]>temp;k=k-i){
					arr[k]=arr[k-i];
					arr[k-i] = temp;
					temp = arr[k-i];
				}
			}
		}
	}
	public static void printArray(int arr[]){
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}
	
}

Output :


printing the array..
12 34 54 2 3 16 18 1 
printing the sorted array..
1 2 3 12 16 18 34 54 


Leave a comment

Design a site like this with WordPress.com
Get started