对于一个int数组,请编写一个希尔排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。保证元素小于等于2000。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
AC代码:
import java.util.*;
public class ShellSort {
public int[] shellSort(int[] A, int n) {
// write code here
int step = n / 2;
for (int i=step; i>0; i--) {
process(A, i, n);
}
return A;
}
public void process(int[] A, int step, int len) {
for (int i=step; i<len; i++) {
int left = i-step;
int right = i;
while(left>=0) {
if (A[left] > A[right]) {
A[left] = A[left] + A[right];
A[right] = A[left] - A[right];
A[left] = A[left] - A[right];
left = left - step;
right = right - step;
} else {
break;
}
}
}
}
}