Codementor Events

Shell Sort

Published Sep 11, 2020Last updated Sep 16, 2020
Shell Sort

using System;
using System.Collections.Generic;
namespace ShellSort
{
// Deriving from the IMfcArchiveSerialization interface is not mandatory
class CArray
{
private int[] arr;
private int upper;
private int numElements;
public CArray(int size)
{
arr = new int[size];
upper = size - 1;
numElements = 0;
}
public void Insert(int item)
{
arr[numElements] = item;
numElements++;
}
public void DisplayElements()
{
for (int i = 0; i <= upper; i++)
Console.Write(arr[i] + " ");
}
public void Clear()
{
for (int i = 0; i <= upper; i++)
arr[i] = 0;
numElements = 0;
}
public void ShellSort()
{
int inner, temp;
int h = 1;
while (h <= numElements / 3)
h = h * 3 + 1;
while (h > 0)
{
for (int outer = h; h<= numElements - 1; outer++)
{
temp = arr[outer];
inner = outer;
while ((inner > h - 1) && arr[inner - h] >= temp)
{
arr[inner] = arr[inner - h];
inner -= h;
}
arr[inner] = temp;
}
h = (h - 1) / 3;
}
}
}
class Program
{
static void Main(string[] args)
{
const int SIZE = 19;
CArray theArray = new CArray(SIZE);
for(int index = 0; index < SIZE; index++)
theArray.Insert((int)(100 * Rnd.Next()%99 + 1));
Console.WriteLine();
theArray.DisplayElements();
Console.WriteLine();
theArray.ShellSort();
theArray.DisplayElements();
}
}
}

Discover and read more posts from Phan Quoc Thai
get started