对于一个int数组,请编写一个希尔排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。保证元素小于等于2000。
测试样例:
[1,2,3,5,3],6
[1,5]
#include<iostream>
#include<string>
using namespace std;
class ShellSort {
public:
void display(int * A,int n){
for (int i = 0; i < n; i++){
printf("%d ",A[i]);
}
printf("\n");
}
void swap(int * A,int * B){
int temp = *A;
*A = *B;
*B = temp;
}
int* shellSort(int* A,int n) {
// write code here
int step = 3;
while (step > 0){
for (int i = step; i < n; i++){
int j = i;
while (j >= step){
if (A[j] < A[j - step]){
swap(A + j,A + j - step);
j -= step;
}
else{
break;
}
}//end while j
}//end for
step--;
}
return A;
}
};
int main()
{
ShellSort s;
int A[] = { 54,35,48,36,27,12,44,8,14,26,17,28 };
int n = 13;
s.shellSort(A,n);
s.display(A,n);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。