首页 > 编程语言 > 详细

希尔排序

时间:2021-05-23 23:22:00      阅读:21      评论:0      收藏:0      [点我收藏+]

这次来看看希尔排序:

 1 #include <iostream>
 2 #define N 100
 3 using namespace std;
 4 class ShellSort
 5 {
 6 public:
 7     void shellSort(int arr[], int length)
 8     {
 9         for (increment = length / 2; increment > 0; increment /= 2) {  //低级错误以后请不要再犯了,这里不是increment/2.
10             for (int i = increment; i < length; i++) {
11                 int j = i;
12                 while (j - increment >= 0)
13                 {
14                     if (arr[j] < arr[j - increment]) {
15                         swap(&arr[j], &arr[j - increment]);
16                         j -= increment;
17                     }
18                     else {
19                         break;
20                     }
21                 }
22             }
23         }
24     }
25 
26 private:
27     int increment; //设置一个增量
28     void swap(int* a, int* b)
29     {
30         int temp = *a;
31         *a = *b;
32         *b = temp;
33     }
34 };
35 
36 int main()
37 {
38     int data[N], len;
39     cout << "请输入数组长度:";
40     cin >> len;
41     cout << "请输入数组元素:";
42     for (int i = 0; i < len; i++) {
43         cin >> data[i];
44     }
45     ShellSort ss;
46     ss.shellSort(data, len);
47     cout << "采用希尔排序后的数组是:";
48     for (int i = 0; i < len; i++) {
49         cout << data[i] << " ";
50     }
51     return 0;
52 }

主要思想就是把一个数组不断地进行分组,组内进行排序,以达到一个大致排好序了的过程,然后继续分组,不过这个组间隔要变小,不断重复这个过程就可以。

希尔排序

原文:https://www.cnblogs.com/EvanTheGreat/p/14801865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!