Techiehook Techiehook
Updated date Jun 12, 2024
In this program, we will explore how to sort a list of numbers using Shell Sort in C#.

Shell Sort:

Shell sort is used to sort an array by iteratively placing the elements of that array into smaller sub-arrays and is followed by insertion sort. Counting on this idea, shell sort does not compare elements in the same way as the simple inserting sort does, but instead, it compares elements that are far from each other, not the ones near each other.

Below simple C# program shows how to do the shell sort easily.

using System;

class ShellSort {
    public static void Sort(int[] array) {
        int n = array.Length;        

        for (int gap = n / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < n; i += 1) {
                int temp = array[i];
                int j;
                for (j = i; j >= gap && array[j - gap] > temp; j -= gap)
                    array[j] = array[j - gap];
                array[j] = temp;
            }
        }
    }    
    
    public static void PrintArray(int[] array) {
        int n = array.Length;
        for (int i = 0; i < n; i++)
            Console.Write(array[i] + " ");
        Console.WriteLine();
    }    

    public static void Main(string[] args) {
        int[] array = { 12, 34, 54, 2, 3 };
        Console.WriteLine("Array before sorting:");
        PrintArray(array);
        Sort(array );
        Console.WriteLine("Array after sorting:");
        PrintArray(array);
    }
}

Output:

Array before sorting:
12 34 54 2 3 
Array after sorting:
2 3 12 34 54

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!