Implementing quicksort algorithm

前端 未结 7 1287
走了就别回头了
走了就别回头了 2021-02-01 19:48

I found quicksort algorithm from this book

\"\"

This is the algorithm

QUICKSORT (A, p, r)
i         


        
7条回答
  •  梦毁少年i
    2021-02-01 20:05

    A Simple Quick Sort Implementation.

    https://github.com/bharathkumarms/AlgorithmsMadeEasy/blob/master/AlgorithmsMadeEasy/QuickSort.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace AlgorithmsMadeEasy
    {
        class QuickSort
        {
            public void QuickSortMethod()
            {
                var input = System.Console.ReadLine();
                string[] sInput = input.Split(' ');
                int[] iInput = Array.ConvertAll(sInput, int.Parse);
    
                QuickSortNow(iInput, 0, iInput.Length - 1);
    
                for (int i = 0; i < iInput.Length; i++)
                {
                    Console.Write(iInput[i] + " ");
                }
    
                Console.ReadLine();
            }
    
            public static void QuickSortNow(int[] iInput, int start, int end)
            {
                if (start < end)
                {
                    int pivot = Partition(iInput, start, end);
                    QuickSortNow(iInput, start, pivot - 1);
                    QuickSortNow(iInput, pivot + 1, end);
                }
            }
    
            public static int Partition(int[] iInput, int start, int end)
            {
                int pivot = iInput[end];
                int pIndex = start;
    
                for (int i = start; i < end; i++)
                {
                    if (iInput[i] <= pivot)
                    {
                        int temp = iInput[i];
                        iInput[i] = iInput[pIndex];
                        iInput[pIndex] = temp;
                        pIndex++;
                    }
                }
    
                int anotherTemp = iInput[pIndex];
                iInput[pIndex] = iInput[end];
                iInput[end] = anotherTemp;
                return pIndex;
            }
        }
    }
    
    /*
    Sample Input:
    6 5 3 2 8
    
    Calling Code:
    QuickSort qs = new QuickSort();
    qs.QuickSortMethod();
    */
    

提交回复
热议问题