希尔排序
#include <iostream>using namespace std;
int main()
{
int arr;
int num;
for (int i = 0; i < 10; i++)
{
cin >> num;
arr = num;
}
for (int gap = sizeof(arr) / 2 / 2; gap > 0; gap/=2)
{
for (int j = gap; j >=0; j--)
{
int temp = arr;
int k;
for (k = j+gap; k<sizeof(arr)/2 and temp > arr; k = k+gap)
{
arr = arr;
}
arr = temp;
}
}
for (int i = 0; i < 10; i++)
{
cout << arr << endl;
}
return 0;
}这个希尔排序为什么不对 循环那里有问题,你用j >= 0可能会导致越界,用j >= gap保证arr不会越界;然后就是temp,你的循环条件为temp > arr,当temp小于等于arr时,循环就会结束。应该改为temp < arr。
#include <iostream>
using namespace std;
int main()
{
int arr;
int num;
for (int i = 0; i < 10; i++)
{
cin >> num;
arr = num;
}
for (int gap = sizeof(arr) / sizeof(arr) / 2; gap > 0; gap /= 2)
{
for (int j = gap; j < sizeof(arr) / sizeof(arr); j++)
{
int temp = arr;
int k;
for (k = j; k >= gap && temp < arr; k -= gap)
{
arr = arr;
}
arr = temp;
}
}
for (int i = 0; i < 10; i++)
{
cout << arr << endl;
}
return 0;
}
如果是逆序,就修改temp<arr为大于就可以
#include <iostream>
using namespace std;
int main()
{
int arr;
int num;
for (int i = 0; i < 10; i++)
{
cin >> num;
arr = num;
}
for (int gap = sizeof(arr) / sizeof(arr) / 2; gap > 0; gap /= 2)
{
for (int j = gap; j < sizeof(arr) / sizeof(arr); j++)
{
int temp = arr;
int k;
for (k = j; k >= gap && temp > arr; k -= gap)
{
arr = arr;
}
arr = temp;
}
}
for (int i = 9; i >= 0; i--)
{
cout << arr << endl;
}
return 0;
}
页:
[1]