Saturday 9 September 2017

Java Code for shell sort

Problem:

Java Code for Shell Sort

Solution:

package array.programs;

import java.util.Arrays;

public class ShellSort {

private static int ia[] = { 1, 54, 6, 3, 78, 34, 12, 45, 56, 3 };

private static int[] shellSort(int[] a) {
//the increment;
int step = a.length / 2;

// The result has mostly sorted at the previous step of step=1;
//Just change the condition step> = 1 to step > 1 if you want to observe it ;
while (step >= 1) {

for (int i = step; i <a.length; i++) {
int temp = a[i];
int j;

// use insert sort to sort the part of a;
for (j = i - step; j >= 0 && a[j] > temp; j -= step) {
a[j + step] = a[j];
}
a[j + step] = temp;
}
//narrow the increment.
step = step / 2;
}
return a;
}


public static void main(String[] args) {
System.out.println(Arrays.toString(shellSort(ia)));
}
}


Output:

[1, 3, 3, 6, 12, 34, 45, 54, 56, 78]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...