Sort a Given List of Numbers Using a Shell Sort - C Data Structure

C examples for Data Structure:Sort

Description

Sort a Given List of Numbers Using a Shell Sort

Demo Code

#include<stdio.h>

int myArray[20];/*  ww  w.  j a va 2 s.  com*/
int count = 10;

void shellSort()
{
  int in, out;
  int insert;
  int gap = 1;
  int elements = count;
  int i = 0;
  while(gap <= elements/3)
    gap = gap * 3 + 1;
  while(gap > 0) {
    for(out = gap; out < elements; out++) {
      insert = myArray[out];
      in = out;
      while(in > gap -1 && myArray[in - gap] >= insert) {
        myArray[in] = myArray[in - gap];
        in -= gap;
      }
      myArray[in] = insert;
    }
    gap = (gap -1) /3;
    i++;
  }
}

void main() {
  printf("Enter the 10 integers for shell sort separated by white spaces: \n");
  for (int i=0; i < count; i++)
      scanf("%d", &myArray[i]);
  fflush(stdin);
  shellSort();
  printf("Sorted List: ");
  for(int i = 0; i < count; i++)
      printf("%d ", myArray[i]);
  printf("\nThank you.\n");
}

Result


Related Tutorials