CSharp: Sorting Algorithms

 

/*****************************************************************//**
 * \file    SortingAlgorithm.cs
 * \brief  csharp Sorting Algorithms 算法
 * IDE  vs 2022 C#  .net 6.0
 * \author geovindu,Geovin Du,涂聚文
 * \date   September 28 2023
 *********************************************************************/


using System.Collections.Generic;
using System.Collections;


/**
 * 
 */
namespace SortingAlgorithms
{

    /// <summary>
    /// 排序算法
    /// </summary>
    public class SortingAlgorithm
    {



        /// <summary>
        /// 1.Bubble Sort冒泡排序法
        /// </summary>
        /// <param name="arr"></param>      
        public static void BubbleSort(int[] arrry)
        {
            int n = arrry.Length;
            int i, j, temp;
            bool swapped;
            for (i = 0; i < n - 1; i++)
            {
                swapped = false;
                for (j = 0; j < n - i - 1; j++)
                {
                    if (arrry[j] > arrry[j + 1])
                    {

                        // Swap arr[j] and arr[j+1]
                        temp = arrry[j];
                        arrry[j] = arrry[j + 1];
                        arrry[j + 1] = temp;
                        swapped = true;
                    }
                }

                // If no two elements were
                // swapped by inner loop, then break
                if (swapped == false)
                    break;
            }
        }
        /// <summary>
        /// 打印数组内容
        /// </summary>
        /// <param name="arrry"></param>
         public static void printArray(int[] arrry)
        {
            int i;
            int size = arrry.Length;
            for (i = 0; i < size; i++)
                Console.Write(arrry[i] + " ");
            Console.WriteLine();
        }

        /// <summary>
        /// 2.Selection Sort 选择排序
        /// 
        /// </summary>
        /// <param name="arr"></param>
        public static void SelectionSort(int[] arrry)
        {
            int n = arrry.Length;

            // One by one move boundary of unsorted subarray
            for (int i = 0; i < n - 1; i++)
            {
                // Find the minimum element in unsorted array
                int min_idx = i;
                for (int j = i + 1; j < n; j++)
                    if (arrry[j] < arrry[min_idx])
                        min_idx = j;

                // Swap the found minimum element with the first
                // element
                int temp = arrry[min_idx];
                arrry[min_idx] = arrry[i];
                arrry[i] = temp;
            }
        }
        /// <summary>
        /// 3. 插入排序 Insertion Sort
        /// </summary>
        /// <param name="arrry"></param>
        public static void InsertionSort(int[] arrry)
        {
            int n = arrry.Length;
            for (int i = 1; i < n; ++i)
            {
                int key = arrry[i];
                int j = i - 1;

                // Move elements of arr[0..i-1],
                // that are greater than key,
                // to one position ahead of
                // their current position
                while (j >= 0 && arrry[j] > key)
                {
                    arrry[j + 1] = arrry[j];
                    j = j - 1;
                }
                arrry[j + 1] = key;
            }
        }

        /// <summary>
        /// A utility function to swap two elements
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        private static void quickSwap(int[] arr, int i, int j)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }

        // This function takes last element as pivot,
        // places the pivot element at its correct position
        // in sorted array, and places all smaller to left
        // of pivot and all greater elements to right of pivot
        private static int partition(int[] arr, int low, int high)
        {
            // Choosing the pivot
            int pivot = arr[high];

            // Index of smaller element and indicates
            // the right position of pivot found so far
            int i = (low - 1);

            for (int j = low; j <= high - 1; j++)
            {

                // If current element is smaller than the pivot
                if (arr[j] < pivot)
                {

                    // Increment index of smaller element
                    i++;
                    quickSwap(arr, i, j);
                }
            }
            quickSwap(arr, i + 1, high);
            return (i + 1);
        }

        // The main function that implements QuickSort
        // arr[] --> Array to be sorted,
        // low --> Starting index,
        // high --> Ending index
        /// <summary>
        /// 4 Quick Sort 快速排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="low"></param>
        /// <param name="high"></param>
        public static void quickSort(int[] arr, int low, int high)
        {
            if (low < high)
            {

                // pi is partitioning index, arr[p]
                // is now at right place
                int pi = partition(arr, low, high);

                // Separately sort elements before
                // and after partition index
                quickSort(arr, low, pi - 1);
                quickSort(arr, pi + 1, high);
            }
        }


        // Merges two subarrays of []arr.
        // First subarray is arr[l..m]
        // Second subarray is arr[m+1..r]
        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="l"></param>
        /// <param name="m"></param>
        /// <param name="r"></param>
        private static void merge(int[] arr, int l, int m, int r)
        {
            // Find sizes of two
            // subarrays to be merged
            int n1 = m - l + 1;
            int n2 = r - m;

            // Create temp arrays
            int[] L = new int[n1];
            int[] R = new int[n2];
            int i, j;

            // Copy data to temp arrays
            for (i = 0; i < n1; ++i)
                L[i] = arr[l + i];
            for (j = 0; j < n2; ++j)
                R[j] = arr[m + 1 + j];

            // Merge the temp arrays

            // Initial indexes of first
            // and second subarrays
            i = 0;
            j = 0;

            // Initial index of merged
            // subarray array
            int k = l;
            while (i < n1 && j < n2)
            {
                if (L[i] <= R[j])
                {
                    arr[k] = L[i];
                    i++;
                }
                else
                {
                    arr[k] = R[j];
                    j++;
                }
                k++;
            }

            // Copy remaining elements
            // of L[] if any
            while (i < n1)
            {
                arr[k] = L[i];
                i++;
                k++;
            }

            // Copy remaining elements
            // of R[] if any
            while (j < n2)
            {
                arr[k] = R[j];
                j++;
                k++;
            }
        }

        // Main function that
        // sorts arr[l..r] using
        // merge()
        /// <summary>
        /// 5 Merge Sort 合并/归并排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="l"></param>
        /// <param name="r"></param>
        public static void MergeSort(int[] arr, int l, int r)
        {
            if (l < r)
            {

                // Find the middle point
                int m = l + (r - l) / 2;

                // Sort first and second halves
                MergeSort(arr, l, m);
                MergeSort(arr, m + 1, r);

                // Merge the sorted halves
                merge(arr, l, m, r);
            }
        }


        /* Function to calculate length of linked list */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        /// <returns></returns>
        private static int LinkedLength(Node current)
        {
            int count = 0;
            while (current != null)
            {
                current = current.next;
                count++;
            }
            return count;
        }

        /* Merge function of Merge Sort to Merge the two sorted parts
        of the Linked List. We compare the next value of start1 and 
        current value of start2 and insert start2 after start1 if 
        it's smaller than next value of start1. We do this until
        start1 or start2 end. If start1 ends, then we assign next 
        of start1 to start2 because start2 may have some elements
        left out which are greater than the last value of start1. 
        If start2 ends then we assign end2 to end1. This is necessary
        because we use end2 in another function (mergeSort function) 
        to determine the next start1 (i.e) start1 for next
        iteration = end2.next */
        private static Node LinkedMerge(Node start1, Node end1,
                Node start2, Node end2)
        {

            // Making sure that first node of second
            // list is higher.
            Node temp = null;
            if ((start1).data > (start2).data)
            {
                Node t = start1;
                start1 = start2;
                start2 = t;
                t = end1;
                end1 = end2;
                end2 = t;
            }

            // Merging remaining nodes
            Node astart = start1, aend = end1;
            Node bstart = start2, bend = end2;
            Node bendnext = (end2).next;
            while (astart != aend && bstart != bendnext)
            {
                if (astart.next.data > bstart.data)
                {
                    temp = bstart.next;
                    bstart.next = astart.next;
                    astart.next = bstart;
                    bstart = temp;
                }
                astart = astart.next;
            }
            if (astart == aend)
                astart.next = bstart;
            else
                end2 = end1;

            return start1;
        }

        /* MergeSort of Linked List
        The gap is initially 1. It is incremented as 
        2, 4, 8, .. until it reaches the length of the 
        linked list. For each gap, the linked list is 
        sorted around the gap. 
        The prevend stores the address of the last node after
        sorting a part of linked list so that it's next node
        can be assigned after sorting the succeeding list. 
        temp is used to store the next start1 because after 
        sorting, the last node will be different. So it 
        is necessary to store the address of start1 before 
        sorting. We select the start1, end1, start2, end2 for 
        sorting. start1 - end1 may be considered as a list 
        and start2 - end2 may be considered as another list 
        and we are merging these two sorted list in merge 
        function and assigning the starting address to the 
        previous end address. */

        /// <summary>
        /// Iterative Merge Sort for Linked List
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public static Node LinkedMergeSort(Node head)
        {
            if (head == null)
                return head;
            Node start1 = null, end1 = null;
            Node start2 = null, end2 = null;
            Node prevend = null;
            int len = LinkedLength(head);

            for (int gap = 1; gap < len; gap = gap * 2)
            {
                start1 = head;
                while (start1 != null)
                {

                    // If this is first iteration
                    Boolean isFirstIter = false;
                    if (start1 == head)
                        isFirstIter = true;

                    // First part for merging
                    int counter = gap;
                    end1 = start1;
                    while (--counter > 0 && end1.next != null)
                        end1 = end1.next;

                    // Second part for merging
                    start2 = end1.next;
                    if (start2 == null)
                        break;
                    counter = gap;
                    end2 = start2;
                    while (--counter > 0 && end2.next != null)
                        end2 = end2.next;

                    // To store for next iteration.
                    Node temp = end2.next;

                    // Merging two parts.
                    LinkedMerge(start1, end1, start2, end2);

                    // Update head for first iteration, else
                    // append after previous list
                    if (isFirstIter)
                        head = start1;
                    else
                        prevend.next = start1;

                    prevend = end2;
                    start1 = temp;
                }
                prevend.next = start1;
            }
            return head;
        }


        /* Given a reference (pointer to 
        pointer) to the head of a list 
        and an int, push a new node on 
        the front of the list. */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="head_ref"></param>
        /// <param name="new_data"></param>
        /// <returns></returns>
        public static Node LinkedPush(Node head_ref,int new_data)
        {
            Node new_node = new Node();
            new_node.data = new_data;
            new_node.next = (head_ref);
            (head_ref) = new_node;
            return head_ref;
        }
        /// <summary>
        /// 6 Counting Sort 计数排序
        /// </summary>
        /// <param name="inputArray"></param>
        /// <returns></returns>

        public static List<int> countSort(List<int> inputArray)
        {
            int N = inputArray.Count();
            int M = 0;

            for (int i = 0; i < N; i++)
            {
                M = Math.Max(M, inputArray[i]);
            }

            int[] countArray = new int[M + 1];

            for (int i = 0; i < N; i++)
            {
                countArray[inputArray[i]]++;
            }

            for (int i = 1; i <= M; i++)
            {
                countArray[i] += countArray[i - 1];
            }

            List<int> outputArray = new List<int>();// new int[N];

            for (int i = N - 1; i >= 0; i--)
            {
                outputArray[countArray[inputArray[i]] - 1] = inputArray[i];
                countArray[inputArray[i]]--;
            }

            return outputArray;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int getMax(int[] arr, int n)
        {
            int mx = arr[0];
            for (int i = 1; i < n; i++)
                if (arr[i] > mx)
                    mx = arr[i];
            return mx;
        }

        // A function to do counting sort of arr[] according to
        // the digit represented by exp.
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        /// <param name="exp"></param>
        public static void radixCountSort(int[] arr, int n, int exp)
        {
            int[] output = new int[n]; // output array
            int i;
            int[] count = new int[10];

            // initializing all elements of count to 0
            for (i = 0; i < 10; i++)
                count[i] = 0;

            // Store count of occurrences in count[]
            for (i = 0; i < n; i++)
                count[(arr[i] / exp) % 10]++;

            // Change count[i] so that count[i] now contains
            // actual
            //  position of this digit in output[]
            for (i = 1; i < 10; i++)
                count[i] += count[i - 1];

            // Build the output array
            for (i = n - 1; i >= 0; i--)
            {
                output[count[(arr[i] / exp) % 10] - 1] = arr[i];
                count[(arr[i] / exp) % 10]--;
            }

            // Copy the output array to arr[], so that arr[] now
            // contains sorted numbers according to current
            // digit
            for (i = 0; i < n; i++)
                arr[i] = output[i];
        }

        // The main function to that sorts arr[] of size n using
        // Radix Sort
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void radixSort(int[] arr, int n)
        {
            // Find the maximum number to know number of digits
            int m = getMax(arr, n);

            // Do counting sort for every digit. Note that
            // instead of passing digit number, exp is passed.
            // exp is 10^i where i is current digit number
            for (int exp = 1; m / exp > 0; exp *= 10)
                radixCountSort(arr, n, exp);
        }

        // Insertion sort function to sort individual buckets
         private  static void InsertionSort(List<float> bucket)
        {
            for (int i = 1; i < bucket.Count; ++i)
            {
                float key = bucket[i];
                int j = i - 1;
                while (j >= 0 && bucket[j] > key)
                {
                    bucket[j + 1] = bucket[j];
                    j--;
                }
                bucket[j + 1] = key;
            }
        }

        // Function to sort arr[] of size n using bucket sort
        /// <summary>
        /// 8 Bucket Sort 桶排序
        /// </summary>
        /// <param name="arr"></param>
        public static void BucketSort(float[] arr)
        {
            int n = arr.Length;

            // 1) Create n empty buckets
            List<float>[] buckets = new List<float>[n];
            for (int i = 0; i < n; i++)
            {
                buckets[i] = new List<float>();
            }

            // 2) Put array elements in different buckets
            for (int i = 0; i < n; i++)
            {
                int bi = (int)(n * arr[i]);
                buckets[bi].Add(arr[i]);
            }

            // 3) Sort individual buckets using insertion sort
            for (int i = 0; i < n; i++)
            {
                InsertionSort(buckets[i]);
            }

            // 4) Concatenate all buckets into arr[]
            int index = 0;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < buckets[i].Count; j++)
                {
                    arr[index++] = buckets[i][j];
                }
            }
        }

        /// <summary>
        /// 9 Heap Sort 堆排序
        /// </summary>
        /// <param name="arr"></param>
        public static void HeapSort(int[] arr)
        {
            int N = arr.Length;

            // Build heap (rearrange array)
            for (int i = N / 2 - 1; i >= 0; i--)
                heapify(arr, N, i);

            // One by one extract an element from heap
            for (int i = N - 1; i > 0; i--)
            {
                // Move current root to end
                int temp = arr[0];
                arr[0] = arr[i];
                arr[i] = temp;

                // call max heapify on the reduced heap
                heapify(arr, i, 0);
            }
        }

        // To heapify a subtree rooted with node i which is
        // an index in arr[]. n is size of heap
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="N"></param>
        /// <param name="i"></param>
         private static void heapify(int[] arr, int N, int i)
        {
            int largest = i; // Initialize largest as root
            int l = 2 * i + 1; // left = 2*i + 1
            int r = 2 * i + 2; // right = 2*i + 2

            // If left child is larger than root
            if (l < N && arr[l] > arr[largest])
                largest = l;

            // If right child is larger than largest so far
            if (r < N && arr[r] > arr[largest])
                largest = r;

            // If largest is not root
            if (largest != i)
            {
                int swap = arr[i];
                arr[i] = arr[largest];
                arr[largest] = swap;

                // Recursively heapify the affected sub-tree
                heapify(arr, N, largest);
            }
        }


        /* function to sort arr using shellSort */
        /// <summary>
        /// 10 Shell Sort 希尔排序
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static int ShellSort(int[] arr)
        {
            int n = arr.Length;

            // Start with a big gap, 
            // then reduce the gap
            for (int gap = n / 2; gap > 0; gap /= 2)
            {
                // Do a gapped insertion sort for this gap size.
                // The first gap elements a[0..gap-1] are already
                // in gapped order keep adding one more element
                // until the entire array is gap sorted
                for (int i = gap; i < n; i += 1)
                {
                    // add a[i] to the elements that have
                    // been gap sorted save a[i] in temp and
                    // make a hole at position i
                    int temp = arr[i];

                    // shift earlier gap-sorted elements up until
                    // the correct location for a[i] is found
                    int j;
                    for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                        arr[j] = arr[j - gap];

                    // put temp (the original a[i]) 
                    // in its correct location
                    arr[j] = temp;
                }
            }
            return 0;
        }

        /// <summary>
        ///  11 Linear Search线性搜索
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="N"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int LinearSearch(int[] arr, int N, int x)
        {
            for (int i = 0; i < N; i++)
            {
                if (arr[i] == x)
                    return i;
            }
            return -1;
        }

        /// <summary>
        /// 12 Binary Search  二分查找
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int binarySearch(int[] arr, int x)
        {
            int low = 0, high = arr.Length - 1;
            while (low <= high)
            {
                int mid = low + (high - low) / 2;

                // Check if x is present at mid
                if (arr[mid] == x)
                    return mid;

                // If x greater, ignore left half
                if (arr[mid] < x)
                    low = mid + 1;

                // If x is smaller, ignore right half
                else
                    high = mid - 1;
            }

            // If we reach here, then element was
            // not present
            return -1;
        }

        static int bingo;
        static int nextBingo;

        // Function for finding the maximum and minimum element
        // of
        // the Array
        /// <summary>
        /// 
        /// </summary>
        /// <param name="vec"></param>
        /// <param name="n"></param>
        static void maxMin(int[] vec, int n)
        {
            for (int i = 1; i < n; i++)
            {
                bingo = Math.Min(bingo, vec[i]);
                nextBingo = Math.Max(nextBingo, vec[i]);
            }
        }

        // Function to sort the array
        /// <summary>
        /// 13 Bingo Sort宾果排序
        /// </summary>
        /// <param name="vec"></param>
        /// <param name="n"></param>
        /// <returns></returns>
         public  static int[] bingoSort(int[] vec, int n)
        {
            bingo = vec[0];
            nextBingo = vec[0];
            maxMin(vec, n);
            int largestEle = nextBingo;
            int nextElePos = 0;
            while (bingo < nextBingo)
            {
                // Will keep the track of the element position
                // to
                // shifted to their correct position
                int startPos = nextElePos;
                for (int i = startPos; i < n; i++)
                {
                    if (vec[i] == bingo)
                    {
                        int temp = vec[i];
                        vec[i] = vec[nextElePos];
                        vec[nextElePos] = temp;
                        nextElePos = nextElePos + 1;
                    }
                    // Here we are finding the next Bingo
                    // Element for the next pass
                    else if (vec[i] < nextBingo)
                        nextBingo = vec[i];
                }
                bingo = nextBingo;
                nextBingo = largestEle;
            }
            return vec;
        }


        const int RUN = 32;

        // This function sorts array from left 
        // index to to right index which is 
        // of size atmost RUN 
        private static void insertionSort(int[] arr, int left, int right)
        {
            for (int i = left + 1; i <= right; i++)
            {
                int temp = arr[i];
                int j = i - 1;
                while (j >= left && arr[j] > temp)
                {
                    arr[j + 1] = arr[j];
                    j--;
                }
                arr[j + 1] = temp;
            }
        }

        // Merge function merges the sorted runs 
        /// <summary>
        /// 14 Tim Sort
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="l"></param>
        /// <param name="m"></param>
        /// <param name="r"></param>
        private static void timMerge(int[] arr, int l, int m, int r)
        {

            // original array is broken in two parts 
            // left and right array 
            int len1 = m - l + 1, len2 = r - m;
            int[] left = new int[len1];
            int[] right = new int[len2];
            for (int x = 0; x < len1; x++)
                left[x] = arr[l + x];
            for (int x = 0; x < len2; x++)
                right[x] = arr[m + 1 + x];

            int i = 0;
            int j = 0;
            int k = l;

            // After comparing, we merge those two array 
            // in larger sub array 
            while (i < len1 && j < len2)
            {
                if (left[i] <= right[j])
                {
                    arr[k] = left[i];
                    i++;
                }
                else
                {
                    arr[k] = right[j];
                    j++;
                }
                k++;
            }

            // Copy remaining elements 
            // of left, if any 
            while (i < len1)
            {
                arr[k] = left[i];
                k++;
                i++;
            }

            // Copy remaining element 
            // of right, if any 
            while (j < len2)
            {
                arr[k] = right[j];
                k++;
                j++;
            }
        }

        // Iterative Timsort function to sort the 
        // array[0...n-1] (similar to merge sort) 
        void timSort(int[] arr, int n)
        {

            // Sort individual subarrays of size RUN 
            for (int i = 0; i < n; i += RUN)
                insertionSort(arr, i, Math.Min((i + RUN - 1), (n - 1)));

            // Start merging from size RUN (or 32). 
            // It will merge 
            // to form size 64, then 128, 256 
            // and so on .... 
            for (int size = RUN; size < n; size = 2 * size)
            {

                // pick starting point of 
                // left sub array. We 
                // are going to merge 
                // arr[left..left+size-1] 
                // and arr[left+size, left+2*size-1] 
                // After every merge, we 
                // increase left by 2*size 
                for (int left = 0; left < n; left += 2 * size)
                {

                    // Find ending point of 
                    // left sub array 
                    // mid+1 is starting point 
                    // of right sub array 
                    int mid = left + size - 1;
                    int right = Math.Min((left + 2 * size - 1), (n - 1));

                    // merge sub array arr[left.....mid] & 
                    // arr[mid+1....right] 
                    if (mid < right)
                        timMerge(arr, left, mid, right);
                }
            }
        }


        // To find gap between elements
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gap"></param>
        /// <returns></returns>
         private  static int getNextGap(int gap)
        {
            // Shrink gap by Shrink factor
            gap = (gap * 10) / 13;
            if (gap < 1)
                return 1;
            return gap;
        }

        // Function to sort arr[] using Comb Sort
        /// <summary>
        ///  15  Comb Sort
        /// </summary>
        /// <param name="arr"></param>
        public static void CombSort(int[] arr)
        {
            int n = arr.Length;

            // initialize gap
            int gap = n;

            // Initialize swapped as true to 
            // make sure that loop runs
            bool swapped = true;

            // Keep running while gap is more than 
            // 1 and last iteration caused a swap
            while (gap != 1 || swapped == true)
            {
                // Find next gap
                gap = getNextGap(gap);

                // Initialize swapped as false so that we can
                // check if swap happened or not
                swapped = false;

                // Compare all elements with current gap
                for (int i = 0; i < n - gap; i++)
                {
                    if (arr[i] > arr[i + gap])
                    {
                        // Swap arr[i] and arr[i+gap]
                        int temp = arr[i];
                        arr[i] = arr[i + gap];
                        arr[i + gap] = temp;

                        // Set swapped
                        swapped = true;
                    }
                }
            }
        }

        /// <summary>
        /// 16  Pigeonhole Sort 鸽巢排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void pigeonholeSort(int[] arr, int n)
        {
            int min = arr[0];
            int max = arr[0];
            int range, i, j, index;

            for (int a = 0; a < n; a++)
            {
                if (arr[a] > max)
                    max = arr[a];
                if (arr[a] < min)
                    min = arr[a];
            }

            range = max - min + 1;
            int[] phole = new int[range];

            for (i = 0; i < n; i++)
                phole[i] = 0;

            for (i = 0; i < n; i++)
                phole[arr[i] - min]++;


            index = 0;

            for (j = 0; j < range; j++)
                while (phole[j]-- > 0)
                    arr[index++] = j + min;

        }
        /// <summary>
        /// 17 Cycle Sort 循环排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void CycleSort(int[] arr, int n)
        {
            int i = 0;
            while (i < n)
            {
                // as array is of 1 based indexing so the
                // correct position or index number of each
                // element is element-1 i.e. 1 will be at 0th
                // index similarly 2 correct index will 1 so
                // on...
                int correctpos = arr[i] - 1;
                if (arr[i] < n && arr[i] != arr[correctpos])
                {
                    // if array element should be lesser than
                    // size and array element should not be at
                    // its correct position then only swap with
                    // its correct position or index value
                    CycleSwap(arr, i, correctpos);
                }
                else
                {
                    // if element is at its correct position
                    // just increment i and check for remaining
                    // array elements
                    i++;
                }
            }
            Console.Write("\nAfter sort : ");
            for (int index = 0; index < n; index++)
                Console.Write(arr[index] + " ");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="i"></param>
        /// <param name="correctpos"></param>
        private static void CycleSwap(int[] arr, int i, int correctpos)
        {
            // swap elements with their correct indexes
            int temp = arr[i];
            arr[i] = arr[correctpos];
            arr[correctpos] = temp;
        }

        /// <summary>
        /// 18 Cocktail Sort 鸡尾酒排序
        /// </summary>
        /// <param name="arr"></param>
        public static void cocktailSort(List<int> arr)
        {
            int n = arr.Count;
            bool swapped = true;
            int start = 0;
            int end = n - 1;
            while (swapped)
            {
                // Move from left to right
                swapped = false;
                for (int i = start; i < end; i++)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        cocktailSwap(arr, i, i + 1);
                        swapped = true;
                    }
                }
                if (!swapped)
                {
                    break;
                }
                end--;
                // Move from right to left
                swapped = false;
                for (int i = end - 1; i >= start; i--)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        cocktailSwap(arr, i, i + 1);
                        swapped = true;
                    }
                }
                start++;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        private static void cocktailSwap(List<int> arr, int i, int j)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }


        // Define a helper function to merge two sorted lists 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list1"></param>
        /// <param name="list2"></param>
        /// <returns></returns>
        private static List<int> MergeLists(List<int> list1, List<int> list2)
        {
            List<int> result = new List<int>();
            while (list1.Count > 0 && list2.Count > 0)
            {
                if (list1[0] < list2[0])
                {
                    result.Add(list1[0]);
                    list1.RemoveAt(0);
                }
                else
                {
                    result.Add(list2[0]);
                    list2.RemoveAt(0);
                }
            }
            result.AddRange(list1);
            result.AddRange(list2);
            return result;
        }

        // Recursive function to perform strand sort 
        /// <summary>
        /// 19 Strand Sort 经典排序
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public static List<int> PerformStrandSort(List<int> inputList)
        {
            // Base case: if the input list has 1 or fewer elements, it's already sorted 
            if (inputList.Count <= 1)
            {
                return inputList;
            }

            // Initialize a sublist with the first element of the input list 
            List<int> sublist = new List<int>();
            sublist.Add(inputList[0]);
            inputList.RemoveAt(0);

            int i = 0;
            while (i < inputList.Count)
            {
                // If the current element in the input list is greater than the last element in the sublist, 
                // add it to the sublist; otherwise, continue to the next element in the input list. 
                if (inputList[i] > sublist[sublist.Count - 1])
                {
                    sublist.Add(inputList[i]);
                    inputList.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }

            // The sortedSublist contains the sorted elements from the current sublist 
            List<int> sortedSublist = new List<int>(sublist);

            // Recursively sort the remaining part of the input list 
            List<int> remainingList = PerformStrandSort(inputList);

            // Merge the sorted sublist and the sorted remainingList 
            return MergeLists(sortedSublist, remainingList);
        }


        /* To swap values */
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lhs"></param>
        /// <param name="rhs"></param>
        private static void bitonicSwap<T>(ref T lhs, ref T rhs)
        {
            T temp;
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        /// <param name="dir"></param>
        private static void compAndSwap(int[] a, int i, int j, int dir)
        {
            int k;
            if ((a[i] > a[j]))
                k = 1;
            else
                k = 0;
            if (dir == k)
                bitonicSwap(ref a[i], ref a[j]);
        }

        /*It recursively sorts a bitonic sequence in ascending order, 
          if dir = 1, and in descending order otherwise (means dir=0). 
          The sequence to be sorted starts at index position low, 
          the parameter cnt is the number of elements to be sorted.*/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="low"></param>
        /// <param name="cnt"></param>
        /// <param name="dir"></param>
        private static void bitonicMerge(int[] a, int low, int cnt, int dir)
        {
            if (cnt > 1)
            {
                int k = cnt / 2;
                for (int i = low; i < low + k; i++)
                    compAndSwap(a, i, i + k, dir);
                bitonicMerge(a, low, k, dir);
                bitonicMerge(a, low + k, k, dir);
            }
        }

        /* This function first produces a bitonic sequence by recursively 
            sorting its two halves in opposite sorting orders, and then 
            calls bitonicMerge to make them in the same order */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="low"></param>
        /// <param name="cnt"></param>
        /// <param name="dir"></param>
        private static void bitonicSort(int[] a, int low, int cnt, int dir)
        {
            if (cnt > 1)
            {
                int k = cnt / 2;

                // sort in ascending order since dir here is 1 
                bitonicSort(a, low, k, 1);

                // sort in descending order since dir here is 0 
                bitonicSort(a, low + k, k, 0);

                // Will merge whole sequence in ascending order 
                // since dir=1. 
                bitonicMerge(a, low, cnt, dir);
            }
        }

        /* Caller of bitonicSort for sorting the entire array of 
           length N in ASCENDING order */
        /// <summary>
        /// 20  Bitonic Sort 双调排序
        /// </summary>
        /// <param name="a"></param>
        /// <param name="N"></param>
        /// <param name="up"></param>
        public static void BitonicSort(int[] a, int N, int up)
        {
            bitonicSort(a, 0, N, up);
        }

        // Reverses arr[0..i]
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="i"></param>
        private static void PancakeFlip(int[] arr, int i)
        {
            int temp, start = 0;
            while (start < i)
            {
                temp = arr[start];
                arr[start] = arr[i];
                arr[i] = temp;
                start++;
                i--;
            }
        }

        // Recursive function to sort the array using pancake
        // sort
        /// <summary>
        /// 21 Pancake Sort 煎饼排序.
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void PancakeSort(int[] arr, int n)
        {
            // Base case: If the array is already sorted or has
            // only one element, return
            if (n == 1)
                return;

            // Find the index of the maximum element in the
            // unsorted portion of the array
            int mi = 0;
            for (int i = 0; i < n; i++)
            {
                if (arr[i] > arr[mi])
                {
                    mi = i;
                }
            }

            // Move the maximum element to the front of the
            // array if it's not already there
            if (mi != 0)
            {
                PancakeFlip(arr, mi);
            }

            // Flip the entire array to move the maximum element
            // to its correct position
            PancakeFlip(arr, n - 1);

            // Recursively sort the remaining unsorted portion
            // of the array
            PancakeSort(arr, n - 1);
        }

        // To Swap two given numbers
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lhs"></param>
        /// <param name="rhs"></param>
         private  static void bogoSwap<T>(ref T lhs, ref T rhs)
        {
            T temp;
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }

        // To check if array is sorted or not
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        private static bool isSorted(int[] a, int n)
        {
            int i = 0;
            while (i < n - 1)
            {
                if (a[i] > a[i + 1])
                    return false;
                i++;
            }
            return true;
        }

        // To generate permutation of the array
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="n"></param>
        private static void bogoShuffle(int[] a, int n)
        {
            Random rnd = new Random();
            for (int i = 0; i < n; i++)
                bogoSwap(ref a[i], ref a[rnd.Next(0, n)]);
        }

        // Sorts array a[0..n-1] using Bogo sort
        /// <summary>
        /// 22 Bogo Sort  BogoSort or Permutation Sort 置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序
        /// </summary>
        /// <param name="a"></param>
        /// <param name="n"></param>
        public static void bogoSort(int[] a, int n)
        {
            // if array is not sorted then shuffle
            // the array again
            while (!isSorted(a, n))
                bogoShuffle(a, n);
        }
        /// <summary>
        /// 23 Gnome Sort 地精排序,也称侏儒排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void gnomeSort(int[] arr, int n)
        {
            int index = 0;

            while (index < n)
            {
                if (index == 0)
                    index++;
                if (arr[index] >= arr[index - 1])
                    index++;
                else
                {
                    int temp = 0;
                    temp = arr[index];
                    arr[index] = arr[index - 1];
                    arr[index - 1] = temp;
                    index--;
                }
            }
            return;
        }


        // This function will be executed by each thread
        /// <summary>
        /// 
        /// </summary>
        /// <param name="num"></param>
        private static void Routine(int num)
        {
            // Sleeping time is proportional to the number
            Thread.Sleep(num);  // Sleep for 'num' milliseconds
            Console.Write(num + " ");
        }

        // A function that performs sleep sort
        /// <summary>
        /// 24.Sleep Sort 睡眠排序  The King of Laziness / Sorting while Sleeping
        /// </summary>
        /// <param name="arr"></param>
        public static void SleepSort(List<int> arr)
        {
            List<Thread> threads = new List<Thread>();

            // Create a thread for each element in the input array
            foreach (int num in arr)
            {
                Thread thread = new Thread(() => Routine(num));
                threads.Add(thread);
                thread.Start();
            }

            // Wait for all threads to finish
            foreach (Thread thread in threads)
            {
                thread.Join();
            }
        }

        // Function to implement stooge sort 
        /// <summary>
        /// 25 Stooge Sort 臭皮匠排序
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="l"></param>
        /// <param name="h"></param>
        public static void stoogeSort(int[] arr,int l, int h)
        {
            if (l >= h)
                return;

            // If first element is smaller 
            // than last, swap them 
            if (arr[l] > arr[h])
            {
                int t = arr[l];
                arr[l] = arr[h];
                arr[h] = t;
            }

            // If there are more than 2  
            // elements in the array 
            if (h - l + 1 > 2)
            {
                int t = (h - l + 1) / 3;

                // Recursively sort first  
                // 2/3 elements 
                stoogeSort(arr, l, h - t);

                // Recursively sort last 
                // 2/3 elements 
                stoogeSort(arr, l + t, h);

                // Recursively sort first  
                // 2/3 elements again to  
                // confirm 
                stoogeSort(arr, l, h - t);
            }
        }

        // Modifying tag array so that we can access
        // persons in sorted order of salary.
        /// <summary>
        /// 26 Tag Sort (To get both sorted and original)
        /// </summary>
        /// <param name="persons"></param>
        /// <param name="tag"></param>
        public static void TagSort(Person[] persons, int[] tag)
        {
            int n = persons.Length;
            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (persons[tag[i]].GetSalary() >
                            persons[tag[j]].GetSalary())
                    {
                        // Note we are not sorting the
                        // actual Persons array, but only
                        // the tag array
                        int temp = tag[i];
                        tag[i] = tag[j];
                        tag[j] = temp;
                    }
                }
            }
        }


       // static TreeNode root = null;
        // This method mainly 
        // calls insertRec() 
        static void insert(TreeNode root,int key)
        {
            root = insertRec(root, key);
        }

        /* A recursive function to  
          insert a new key in BST */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="root"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        static  TreeNode insertRec(TreeNode root, int key)
        {

            /* If the tree is empty, 
                return a new node */
            if (root == null)
            {
                root = new TreeNode(key);
                return root;
            }

            /* Otherwise, recur 
                down the tree */
            if (key < root.key)
                root.left = insertRec(root.left, key);
            else if (key > root.key)
                root.right = insertRec(root.right, key);

            /* return the root */
            return root;
        }

        // A function to do  
        // inorder traversal of BST 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="root"></param>
        public static void inorderRec(TreeNode root)
        {
            if (root != null)
            {
                inorderRec(root.left);
                Console.Write(root.key + " ");
                inorderRec(root.right);
            }
        }
        /// <summary>
        /// 27 Tree Sort
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="root"></param>
        public static void treeins(int[] arr, TreeNode root)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                insert(root,arr[i]);
            }

        }
        /// <summary>
        /// 28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="n"></param>
        public static void BrickSort(int[] arr, int n)
        {
            // Initially array is unsorted
            bool isSorted = false;

            while (!isSorted)
            {
                isSorted = true;
                int temp = 0;

                // Perform Bubble sort on
                // odd indexed element
                for (int i = 1; i <= n - 2; i = i + 2)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        temp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = temp;
                        isSorted = false;
                    }
                }

                // Perform Bubble sort on
                // even indexed element
                for (int i = 0; i <= n - 2; i = i + 2)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        temp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = temp;
                        isSorted = false;
                    }
                }
            }
            return;
        }


        // Function  for 3-way merge sort process
        /// <summary>
        ///  29. 3-way Merge Sort 3路归并排序
        /// </summary>
        /// <param name="gArray"></param>
        public static void mergeSort3Way(int[] gArray)
        {
            // if array of size is zero returns null
            if (gArray == null)
                return;

            // creating duplicate of given array
            int[] fArray = new int[gArray.Length];

            // copying elements of given array into
            // duplicate array
            for (int i = 0; i < fArray.Length; i++)
                fArray[i] = gArray[i];

            // sort function
            mergeSort3WayRec(fArray, 0, gArray.Length, gArray);

            // copy back elements of duplicate array
            // to given array
            for (int i = 0; i < fArray.Length; i++)
                gArray[i] = fArray[i];
        }

        /* Performing the merge sort algorithm on the
             given array of values in the rangeof indices
             [low, high).  low is minimum index, high is
             maximum index (exclusive) */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gArray"></param>
        /// <param name="low"></param>
        /// <param name="high"></param>
        /// <param name="destArray"></param>
        private static void mergeSort3WayRec(int[] gArray,int low, int high, int[] destArray)
        {
            // If array size is 1 then do nothing
            if (high - low < 2)
                return;

            // Splitting array into 3 parts
            int mid1 = low + ((high - low) / 3);
            int mid2 = low + 2 * ((high - low) / 3) + 1;

            // Sorting 3 arrays recursively
            mergeSort3WayRec(destArray, low, mid1, gArray);
            mergeSort3WayRec(destArray, mid1, mid2, gArray);
            mergeSort3WayRec(destArray, mid2, high, gArray);

            // Merging the sorted arrays
            WayMerge(destArray, low, mid1, mid2, high, gArray);
        }

        /* Merge the sorted ranges [low, mid1), [mid1,
             mid2) and [mid2, high) mid1 is first midpoint
             index in overall range to merge mid2 is second
             midpoint index in overall range to merge*/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gArray"></param>
        /// <param name="low"></param>
        /// <param name="mid1"></param>
        /// <param name="mid2"></param>
        /// <param name="high"></param>
        /// <param name="destArray"></param>
        private static void WayMerge(int[] gArray, int low,int mid1, int mid2, int high,int[] destArray)
        {
            int i = low, j = mid1, k = mid2, l = low;

            // choose smaller of the smallest in the three ranges
            while ((i < mid1) && (j < mid2) && (k < high))
            {
                if (gArray[i].CompareTo(gArray[j]) < 0)
                {
                    if (gArray[i].CompareTo(gArray[k]) < 0)
                        destArray[l++] = gArray[i++];

                    else
                        destArray[l++] = gArray[k++];
                }
                else
                {
                    if (gArray[j].CompareTo(gArray[k]) < 0)
                        destArray[l++] = gArray[j++];
                    else
                        destArray[l++] = gArray[k++];
                }
            }

            // case where first and second ranges have
            // remaining values
            while ((i < mid1) && (j < mid2))
            {
                if (gArray[i].CompareTo(gArray[j]) < 0)
                    destArray[l++] = gArray[i++];
                else
                    destArray[l++] = gArray[j++];
            }

            // case where second and third ranges have
            // remaining values
            while ((j < mid2) && (k < high))
            {
                if (gArray[j].CompareTo(gArray[k]) < 0)
                    destArray[l++] = gArray[j++];

                else
                    destArray[l++] = gArray[k++];
            }

            // case where first and third ranges have
            // remaining values
            while ((i < mid1) && (k < high))
            {
                if (gArray[i].CompareTo(gArray[k]) < 0)
                    destArray[l++] = gArray[i++];
                else
                    destArray[l++] = gArray[k++];
            }

            // copy remaining values from the first range
            while (i < mid1)
                destArray[l++] = gArray[i++];

            // copy remaining values from the second range
            while (j < mid2)
                destArray[l++] = gArray[j++];

            // copy remaining values from the third range
            while (k < high)
                destArray[l++] = gArray[k++];
        }



    }
}

  

/*****************************************************************//**
 * \file    SortExample.cs
 * \brief  csharp Sorting Algorithms 算法
 * IDE  vs 2022 C#  .net 6.0
 * https://www.geeksforgeeks.org/merge-sort/?ref=lbp
 * \author geovindu,Geovin Du,涂聚文
 * \date   September 28 2023
 *********************************************************************/

using System;
using SortingAlgorithms;



namespace BLL
{
     
    /// <summary>
    /// 示例
    /// </summary>
    public class SortExample
    {

        /// <summary>
        /// 1.Bubble Sort冒泡排序法
        /// </summary>
        public static void Bubble()
        {
            int[] geovindu = { 64, 34, 25, 12, 22, 11, 90 };
            int n = geovindu.Length;

            SortingAlgorithm.BubbleSort(geovindu);
            Console.WriteLine("1.Bubble Sorted array:");
            SortingAlgorithms.SortingAlgorithm.printArray(geovindu);

        }
        /// <summary>
        /// 2.Selection Sort 选择排序
        /// </summary>
        public static void Selection()
        {
            int[] geovindu = { 64, 34, 25, 12, 22, 11, 90 };
            int n = geovindu.Length;

            SortingAlgorithm.SelectionSort(geovindu);
            Console.WriteLine("2.Selection Sorted array:");
            SortingAlgorithms.SortingAlgorithm.printArray(geovindu);
        }
        /// <summary>
        /// 3. 插入排序 Insertion Sort
        /// </summary>
        public static void Insertion()
        {
            int[] geovindu = { 64, 34, 25, 12, 22, 11, 90 };
            int n = geovindu.Length;

            SortingAlgorithm.InsertionSort(geovindu);
            Console.WriteLine("3.Insertion Sorted array:");
            SortingAlgorithms.SortingAlgorithm.printArray(geovindu);
        }
        /// <summary>
        /// 4 Quick Sort 快速排序
        /// </summary>

        public static void quickSort()
        {
            int[] arr = { 10, 7, 8, 9, 1, 5 };
            int N = arr.Length;

            // Function call
            SortingAlgorithms.SortingAlgorithm.quickSort(arr, 0, N - 1);
            Console.WriteLine("Sorted array:");
            for (int i = 0; i < N; i++)
                Console.Write(arr[i] + " ");
        }
        /// <summary>
        /// 5 Merge Sort 合并/归并排序
        /// </summary>
        public static void MergeSort()
        {
            int[] arr = { 12, 11, 13, 5, 6, 7 };
            Console.WriteLine("Given array is");
          
            SortingAlgorithms.SortingAlgorithm.MergeSort(arr, 0, arr.Length - 1);
            Console.WriteLine("\nSorted array is");
            int n = arr.Length;
            for (int i = 0; i < n; ++i)
                Console.Write(arr[i] + " ");
            Console.WriteLine();
        }

        /// <summary>
        /// Iterative Merge Sort for Linked List
        /// </summary>
        public static void LinkedMergeSort()
        {
            // start with empty list 
            Node head = null;

            // create linked list 
            // 1.2.3.4.5.6.7 
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 7);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 6);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 5);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 4);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 3);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 2);
            head = SortingAlgorithms.SortingAlgorithm.LinkedPush(head, 1);

            head = SortingAlgorithms.SortingAlgorithm.LinkedMergeSort(head);

            if ((head) == null)
                return;
            Node temp = head;
            while (temp != null)
            {
                Console.Write(temp.data + " ");
                temp = temp.next;
            }
            Console.Write("\n");
        }
        /// <summary>
        ///  6 Counting Sort 计数排序
        /// </summary>
        public static void countSort()
        {

            // Input array
            List<int> inputArray = new List<int>();// { 4, 3, 12, 1, 5, 5, 3, 9 };
            inputArray.Add(4);
            inputArray.Add(3);
            inputArray.Add(12);
            inputArray.Add(1);
            inputArray.Add(5);
            inputArray.Add(5);
            inputArray.Add(3);
            inputArray.Add(9);

            // Output array
            List<int> outputArray = SortingAlgorithms.SortingAlgorithm.countSort(inputArray);
            for (int i = 0; i < inputArray.Count; i++)
                Console.Write(outputArray[i] + " ");
            Console.WriteLine();

        }
        /// <summary>
        /// 7 Radix Sort 基数排序
        /// </summary>
        public static void radixSort()
        {
            int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 };
            int n = arr.Length;

            // Function Call
            SortingAlgorithms.SortingAlgorithm.radixSort(arr, n);
            for (int i = 0; i < n; i++)
                Console.Write(arr[i] + " ");



        }

        /// <summary>
        /// 8 Bucket Sort 桶排序
        /// </summary>
        public static void BucketSort()
        {
            float[] arr = { 0.897f, 0.565f, 0.656f, 0.1234f, 0.665f, 0.3434f };
            SortingAlgorithms.SortingAlgorithm.BucketSort(arr);
            Console.WriteLine("Sorted array is:");
            foreach (float num in arr)
            {
                Console.Write(num + " ");
            }
        }

        /// <summary>
        /// 9 Heap Sort 堆排序
        /// </summary>
        public static void HeapSort()
        {
            int[] arr = { 12, 11, 13, 5, 6, 7 };
            int N = arr.Length;
            // Function call           
            SortingAlgorithms.SortingAlgorithm.HeapSort(arr);
            Console.WriteLine("Sorted array is");        
            for (int i = 0; i < N; ++i)
                Console.Write(arr[i] + " ");
            Console.Read();

        }
        /// <summary>
        /// 10 Shell Sort 希尔排序
        /// </summary>
        public static void ShellSort()
        {

            int[] arr = { 12, 34, 54, 2, 3 };
            Console.Write("Array before sorting :\n");


            SortingAlgorithms.SortingAlgorithm.ShellSort(arr);

            Console.Write("Array after sorting :\n");
            int n = arr.Length;
            for (int i = 0; i < n; ++i)
                Console.Write(arr[i] + " ");
            Console.WriteLine();

        }

        /// <summary>
        /// 11 Linear Search线性搜索
        /// </summary>
        /// <returns></returns>
        public static void LinearSearch()
        {
            int[] arr = { 2, 3, 4, 10, 40 };
            int x = 10;

            // Function call
            int result = SortingAlgorithms.SortingAlgorithm.LinearSearch(arr, arr.Length, x);
            if (result == -1)
                Console.WriteLine(
                    "Element is not present in array");
            else
                Console.WriteLine("Element is present at index "
                                  + result);
        }
        /// <summary>
        /// 12 Binary Search  二分查找
        /// </summary>
        public static void binarySearch()
        {
            int[] arr = { 2, 3, 4, 10, 40 };
            int n = arr.Length;
            int x = 10;
            int result = SortingAlgorithms.SortingAlgorithm.binarySearch(arr, x);
            if (result == -1)
                Console.WriteLine(
                    "Element is not present in array");
            else
                Console.WriteLine("Element is present at "
                                  + "index " + result);
        }
        /// <summary>
        /// 13 Bingo Sort宾果排序
        /// </summary>

        public static void bingoSort()
        {
            int[] arr = { 5, 4, 8, 5, 4, 8, 5, 4, 4, 4 };
            arr = SortingAlgorithms.SortingAlgorithm.bingoSort(arr, arr.Length);
           
            int[] arr2 = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            arr2 = SortingAlgorithms.SortingAlgorithm.bingoSort(arr2, arr2.Length);
          

            int[] arr3 = { 0, 1, 0, 1, 0, 1 };
            arr3 = SortingAlgorithms.SortingAlgorithm.bingoSort(arr3, arr3.Length);
            Console.Write("Sorted Array: ");

            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 
        ///  15  Comb Sort
        /// </summary>
        public static void CombSort()
        {

            int[] arr = { 8, 4, 1, 56, 3, -44, 23, -6, 28, 0 };
            SortingAlgorithms.SortingAlgorithm.CombSort(arr);

            Console.WriteLine("sorted array");
            for (int i = 0; i < arr.Length; ++i)
                Console.Write(arr[i] + " ");

        }
        /// <summary>
        /// 16  Pigeonhole Sort 鸽巢排序
        /// </summary>
        public static void pigeonholeSort()
        {
            int[] arr = {8, 3, 2, 7,
                 4, 6, 8};

            Console.Write("Sorted order is : ");

            SortingAlgorithms.SortingAlgorithm.pigeonholeSort(arr, arr.Length);

            for (int i = 0; i < arr.Length; i++)
                Console.Write(arr[i] + " ");
        }

        /// <summary>
        /// 17 Cycle Sort 循环排序
        /// </summary>
        public static void CycleSort()
        {
            // Code
            int[] arr = { 3, 2, 4, 5, 1 };
            int n = arr.Length;
            Console.Write("Before sort : ");
            for (int i = 0; i < n; i++)
                Console.Write(arr[i] + " ");
            SortingAlgorithms.SortingAlgorithm.CycleSort(arr, n);
        }
        /// <summary>
        /// 18 Cocktail Sort 鸡尾酒排序
        /// </summary>
        public static void cocktailSort()
        {
            List<int> arr = new List<int> { 5, 2, 9, 3, 7, 6 };
            SortingAlgorithms.SortingAlgorithm.cocktailSort(arr);
            foreach (var x in arr)
            {
                Console.Write(x + " ");
            }
            Console.WriteLine();
        }
        /// <summary>
        /// 19 Strand Sort 经典排序
        /// </summary>
        public static void StrandSort()
        {
            List<int> inputList = new List<int> { 10, 5, 30, 40, 2, 4, 9 };

            List<int> outputList = SortingAlgorithms.SortingAlgorithm.PerformStrandSort(inputList);

            foreach (int x in outputList)
            {
                Console.Write(x + " ");
            }


        }
        /// <summary>
        /// 20  Bitonic Sort 双调排序
        /// </summary>
        public static void BitonicSort()
        {
            int[] a = { 3, 7, 4, 8, 6, 2, 1, 5 };
            int N = a.Length;

            int up = 1;   // means sort in ascending order 
            SortingAlgorithms.SortingAlgorithm.BitonicSort(a, N, up);

            Console.Write("Sorted array: \n");
            for (int i = 0; i < N; i++)
                Console.Write(a[i] + " ");
        }
        /// <summary>
        /// 21 Pancake Sort 煎饼排序
        /// </summary>
        public static void PancakeSort()
        {
            int[] arr = { 23, 10, 20, 11, 12, 6, 7 };
            int n = arr.Length;

            SortingAlgorithms.SortingAlgorithm.PancakeSort(arr, n);

            Console.Write("Sorted Array: ");
            for (int i = 0; i < n; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();

        }
        /// <summary>
        /// 22 Bogo Sort  BogoSort or Permutation Sort 置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序
        /// </summary>
        public static void bogoSort()
        {

            int[] a = { 3, 2, 5, 1, 0, 4 };
            int n = a.Length;
            SortingAlgorithms.SortingAlgorithm.bogoSort(a, n);
            Console.Write("Sorted array :\n");
            for (int i = 0; i < n; i++)
                Console.Write(a[i] + " ");
            Console.Write("\n");
        }
        /// <summary>
        /// 23 Gnome Sort 地精排序,也称侏儒排序
        /// </summary>
        public static void gnomeSort()
        {
            int[] arr = { 34, 2, 10, -9 };

            // Function calling 
            SortingAlgorithms.SortingAlgorithm.gnomeSort(arr, arr.Length);

            Console.Write("Sorted sequence after applying Gnome sort: ");

            for (int i = 0; i < arr.Length; i++)
                Console.Write(arr[i] + " ");
        }
        /// <summary>
        /// 24.Sleep Sort 睡眠排序  The King of Laziness / Sorting while Sleeping
        /// </summary>
        public static void SleepSort()
        {
            List<int> arr = new List<int> { 34, 23, 122, 9 };

            SortingAlgorithms.SortingAlgorithm.SleepSort(arr);

        }
        /// <summary>
        /// 25 Stooge Sort 臭皮匠排序
        /// </summary>
        public static void stoogeSort()
        {
            int[] arr = { 2, 4, 5, 3, 1 };
            int n = arr.Length;

            // Calling Stooge Sort function 
            // to sort the array 
            SortingAlgorithms.SortingAlgorithm.stoogeSort(arr, 0, n - 1);

            // Display the sorted array 
            for (int i = 0; i < n; i++)
                Console.Write(arr[i] + " ");
        }
        /// <summary>
        /// 26 Tag Sort (To get both sorted and original)
        /// </summary>
        public static void TagSort()
        {
            // Creating objects and their original
            // order (in tag array)
            int n = 5;
            Person[] persons = new Person[n];
            persons[0] = new Person(0, 233.5f);
            persons[1] = new Person(1, 23f);
            persons[2] = new Person(2, 13.98f);
            persons[3] = new Person(3, 143.2f);
            persons[4] = new Person(4, 3f);
            int[] tag = new int[n];
            for (int i = 0; i < n; i++)
                tag[i] = i;

            // Every Person object is tagged to
            // an element in the tag array.
            Console.WriteLine("Given Person and Tag ");
            for (int i = 0; i < n; i++)
                Console.WriteLine(persons[i] +
                                " : Tag: " + tag[i]);

            // Modifying tag array so that we can access
            // persons in sorted order.
            SortingAlgorithms.SortingAlgorithm.TagSort(persons, tag);

            Console.WriteLine("New Tag Array after " +
                            "getting sorted as per Person[] ");
            for (int i = 0; i < n; i++)
                Console.WriteLine(tag[i]);

            // Accessing persons in sorted (by salary)
            // way using modified tag array.
            for (int i = 0; i < n; i++)
                Console.WriteLine(persons[tag[i]]);
        }
        /// <summary>
        /// 27 Tree Sort
        /// </summary>
        public static void TreeSort()
        {
            // Root of BST 
            TreeNode root = null;
            int[] arr = { 5, 4, 7, 2, 11 };
            SortingAlgorithms.SortingAlgorithm.treeins(arr, root);
            SortingAlgorithms.SortingAlgorithm.inorderRec(root);

        }
        /// <summary>
        /// 28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
        /// </summary>
        public static void BrickSort()
        {
            int[] arr = { 34, 2, 10, -9 };
            int n = arr.Length;

            // Function calling
            SortingAlgorithms.SortingAlgorithm.BrickSort(arr, n);
            for (int i = 0; i < n; i++)
                Console.Write(arr[i] + " ");

            Console.WriteLine(" ");

        }
        /// <summary>
        /// 29. 3-way Merge Sort 3路归并排序
        /// </summary>
        public static void mergeSort3Way()
        {
            // test case of values
            int[] data = new int[] {45, -2, -45, 78,
                            30, -42, 10, 19, 73, 93};
            SortingAlgorithms.SortingAlgorithm.mergeSort3Way(data);
            Console.Write("After 3 way merge sort: ");
            for (int i = 0; i < data.Length; i++)
                Console.Write(data[i] + " ");

        }






    }

}

  

 

 

 

 

调用:

/*****************************************************************//**
 * \file    Program.cs
 * \brief  csharp Sorting Algorithms 算法
 * IDE  vs 2022 C#  .net 6.0
 * \author geovindu
 * \date   September 28 2023
 *********************************************************************/

// See https://aka.ms/new-console-template for more information

using BLL;





Console.WriteLine("Hello, World! 涂聚文 Geovin Du,geovindu, 学习CSharp");
//1.
SortExample.Bubble();
//2.
SortExample.Selection();
//3.
SortExample.Insertion();

  

 

posted @ 2023-09-28 14:57  ®Geovin Du Dream Park™  阅读(22)  评论(0)    收藏  举报