C + + implementation of Shellsort


This example for you to share the C + + implementation of Hill sort specific code, for your reference, the specific content is as follows

1、 Thinking:

Hill sort: also known as reduced incremental sort, is an improved insertion sort algorithm, which is unstable.

Let there be n elements in the sequence of sorting elements. First, an integer gap < n is taken as the interval, and all elements are divided into gap subsequences. All elements with gap distance are placed in the same subsequence, and direct insertion sorting is performed in each subsequence. Then the gap is narrowed and the above subsequence and sorting are repeated.

2、 Implementation procedure:

#include <iostream>
using namespace std;
const int maxSize = 20;
//Hill sort: decrease 1 / 3 every time until d = 1;
//Because the previous increment is relatively large, the interval comparison reduces the number of comparisons, and the parts have been sorted,
//Although D is getting smaller and smaller in the back, because the front is already in order, the insertion in the back needs to be smaller than that in the back
//The number of times to compare is reduced.
template <class T>
void ShellSort(T arr[], const int left, const int right) {
 Int i, J, gap, temp; // gap is the increment
 Gap = right - left + 1; // initial value of increment
 Do {// until the increment value is 1
  Gap = gap / 3 + 1; // find the next increment
  for(i = left + gap; i <= right; i++) {
   if(arr[i] < arr[i-gap]) {
    temp = arr[i];
    j = i - gap;
    do {
     Arr [J + gap] = arr [J]; // move element backward
     J = J - gap; // compare the previous element
    }while(j >= left && temp < arr[j]);
    Arr [J + gap] = temp; // backfill
  } // for
 }while(gap > 1);
} // ShellSort
int main(int argc, const char * argv[]) {
 int i, n, arr[maxSize];
 Cout < "please enter the number of numbers to sort":;
 cin >> n;
 Cout < "please enter the number to sort":;
 for(i = 0; i < n; i++)
  cin >> arr[i];
 Cout < before sorting: < endl;
 for(i = 0; i < n; i++)
  cout << arr[i] << " ";
 cout << endl;
 ShellSort(arr, 0, n-1);
 Cout < after sorting: < endl;
 for(i = 0; i < n; i++)
  cout << arr[i] << " ";
 cout << endl;
 return 0;

Test results:

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Pandas data analysis — detailed explanation of super easy to use groupby

WeChat official account: “Python reads money”If there are any questions or suggestions, please official account message. In the daily data analysis, it is often necessary to analyze the dataDivide into different groups according to one (more) fieldFor example, in the field of e-commerce, the total sales of the whole country are divided by provinces, and […]