Our Feeds

Thursday 17 December 2015

AJITH KP

Shell Sort Solution - C++

Hi GuyZ,
     Shell sort is an alternate version of insertion sort. The algorithm can be read from Wikipedia[^].



Source Code

#include <iostream>
using namespace std;
/*
 Shell Sort Solution - http://www.terminalcoders.blogspot.com
 Ajith Kp [@ajithkp560]
*/
void arrange(int *a, int start, int x, int l){
 int i = start+x;
 while(i<l){
  int val = a[i];
  int pos = i;
  while(pos>=x && a[pos-x]>val){
   a[pos] = a[pos-x];
   pos = pos-x;
  }
  a[pos] = val;
  i++;
 }
}
void shells(int *a, int l){
 int start = l/2;
 while(start>0){
  for(int i=0;i<start;i++){
   arrange(a, i, start, l);
  }
  cout<<"At the size "<<start<<": ";
  for(int i=0;i<l;i++)
   cout<<a[i]<<" ";
  cout<<endl;
  start=start/2;
 }
}
int main(){
 int n, x, a[1024];
 cout<<"Enter limit: ";
 cin>>n;
 cout<<"Enter "<<n<<" items: ";
 for(int i=0;i<n;i++)
  cin>>a[i];
 shells(a, n);
 cout<<"After Sort: ";
 for(int i=0;i<n;i++)
  cout<<a[i]<<" ";
 cout<<endl;
}