Hill Sort (C++)

achieve

  • Hill sorting is also called reduced incremental sorting.
  1. Ideas
  • First divide the entire sequence of records to be sorted into several sub-sequences for direct insertion sorting respectively
    , and when the records in the entire sequence are "basically ordered", then perform direct insertion sorting for all records in sequence.
  1. Code
void shell_insert_sort(int a[], int n, int dk) {
    
    
  if (n < 2) {
    
    
    return;
  }

  int index = 1;
  for (int i = dk; i < n; ++i) {
    
    
    if (a[i] < a[i - dk]) {
    
    
      int j = i - dk;   // 有序序列结尾元素下标
      int val = a[i];  // 待插入元素值
      while ((j >= 0) && (a[j] > val)) {
    
    
        a[j + dk] = a[j];
        j -= dk;
      }
      a[j + dk] = val;
    }

    print(a, n, dk, index);
    ++index;
  }
}

void shell_sort(int a[], int n){
    
    
  int dk = n /2;
  while(dk >=1){
    
    
    shell_insert_sort(a, n, dk);
    dk = dk /2;
  }  
}

test

  1. Code
#include <iostream>

using namespace std;

void print(int a[], int num, int dk, int index) {
    
    
  cout << "dk = " << dk << " index = " <<  index << " : ";
  for (int i = 0; i < num; ++i) {
    
    
    cout << a[i] << " ";
  }
  cout << endl;
}

int main() {
    
    
  int a[] = {
    
    7, 6, 5, 4, 3, 2, 1};
  shell_sort(a, sizeof(a) / sizeof(a[0]));
  cin.get();
  return 0;
}
  1. result
dk = 3 index = 1 : 4 6 5 7 3 2 1
dk = 3 index = 2 : 4 3 5 7 6 2 1
dk = 3 index = 3 : 4 3 2 7 6 5 1
dk = 3 index = 4 : 1 3 2 4 6 5 7
dk = 1 index = 1 : 1 3 2 4 6 5 7
dk = 1 index = 2 : 1 2 3 4 6 5 7
dk = 1 index = 3 : 1 2 3 4 6 5 7
dk = 1 index = 4 : 1 2 3 4 6 5 7
dk = 1 index = 5 : 1 2 3 4 5 6 7
dk = 1 index = 6 : 1 2 3 4 5 6 7

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109390808