Implementing quicksort algorithm

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

I found quicksort algorithm from this book

\"\"

This is the algorithm

QUICKSORT (A, p, r)
i         


        
相关标签:
7条回答
  • 2021-02-01 19:57

    Just in case you want some shorter code for Quicksort:

        IEnumerable<int> QuickSort(IEnumerable<int> i)
        {
            if (!i.Any())
                return i;
            var p = (i.First() + i.Last) / 2 //whichever pivot method you choose
            return QuickSort(i.Where(x => x < p)).Concat(i.Where(x => x == p).Concat(QuickSort(i.Where(x => x > p))));
        }
    

    Get p (pivot) with whatever method is suitable of course.

    0 讨论(0)
  • 2021-02-01 20:02

    A simple generic C# implementation of QuickSort, can use first or last value or any other intermediate value for pivot

    using System;
    
    namespace QuickSort
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] arInt = { 6, 4, 2, 8, 4, 5, 4, 5, 4, 5, 4, 8, 11, 1, 7, 4, 13, 5, 45, -1, 0, -7, 56, 10, 57, 56, 57, 56 };
                GenericQuickSort<int>.QuickSort(arInt, 0, arInt.Length - 1);
    
                string[] arStr = { "Here", "Is", "A", "Cat", "Really", "Fast", "And", "Clever" };
                GenericQuickSort<string>.QuickSort(arStr, 0, arStr.Length - 1); ;
    
                Console.WriteLine(String.Join(',', arInt));
                Console.WriteLine(String.Join(',', arStr));
    
                Console.ReadLine();
            }
    
        }
    
        class GenericQuickSort<T> where T : IComparable
        {
    
            public static void QuickSort(T[] ar, int lBound, int uBound)
            {
                if (lBound < uBound)
                {
                    var loc = Partition(ar, lBound, uBound);
                    QuickSort(ar, lBound, loc - 1);
                    QuickSort(ar, loc + 1, uBound);
                }
            }
    
            private static int Partition(T[] ar, int lBound, int uBound)
            {
                var start = lBound;
                var end = uBound;
    
                var pivot = ar[uBound];
    
                // switch to first value as pivot
                // var pivot = ar[lBound];
    
                while (start < end)
                {
    
                    while (ar[start].CompareTo(pivot) < 0)
                    {
                        start++;
                    }
    
                    while (ar[end].CompareTo(pivot) > 0)
                    {
                        end--;
                    }
    
                    if (start < end)
                    {
                        if (ar[start].CompareTo(ar[end]) == 0)
                        {
                            start++;
                        }
                        else
                        {
                            swap(ar, start, end);
                        }
                    }
                }
    
                return end;
            }
    
            private static void swap(T[] ar, int i, int j)
            {
                var temp = ar[i];
                ar[i] = ar[j];
                ar[j] = temp;
            }
        }
    }
    

    Output:

    -7,-1,0,1,2,4,4,4,4,4,4,5,5,5,5,6,7,8,8,10,11,13,45,56,56,56,57,57

    A,And,Cat,Clever,Fast,Here,Is,Really

    One important thing to notice here is that this optimized and simple code properly handles duplicates. I tried several posted quick sort code. Those do not give correct result for this (integer array) input or just hangs, such as https://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-9.php and http://www.softwareandfinance.com/CSharp/QuickSort_Iterative.html. Therefore, if author also wants to use the code which handles duplicates this would be a good reference.

    0 讨论(0)
  • 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();
    */
    
    0 讨论(0)
  • 2021-02-01 20:11

    In addition to Deestan's answer, you also have this wrong:

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

    It should be:

    for (int j = low; j < high; j++)
    
    0 讨论(0)
  • 2021-02-01 20:11
    Code Implemented with Iteration With last element as Pivot
    <code>https://jsfiddle.net/zishanshaikh/5zxvwoq0/3/    </code>
    
    function quickSort(arr,l,u) {
     if(l>=u)
     {
      return;
     }
    
    
    var pivot=arr[u];
    var pivotCounter=l;
    for(let i=l;i<u;i++)
    {
        if(arr[i] <pivot )
        {
          var temp= arr[pivotCounter];
          arr[pivotCounter]=arr[i] ;
          arr[i]=temp;
          pivotCounter++;
        }
    }
    
    
    var temp2= arr[pivotCounter];
          arr[pivotCounter]=arr[u] ;
          arr[u]=temp2;
    
    
    quickSort(arr,pivotCounter+1,u);
    quickSort(arr,0,pivotCounter-1);
    
    
    
    }
    
    <code>https://jsfiddle.net/zishanshaikh/exL9cdoe/1/</code>
    
    Code With first element as Pivot
    
    
    //Logic For Quick Sort
    function quickSort(arr,l,u) {
     if(l>=u)
     {
      return;
     }
    
    
    var pivot=arr[l];
    var pivotCounter=l+1;
    for(let i=l+1;i<u;i++)
    {
        if(arr[i] <pivot )
        {
          var temp= arr[pivotCounter];
          arr[pivotCounter]=arr[i] ;
          arr[i]=temp;
          pivotCounter++;
        }
    }
    var j=pivotCounter-1;
    var k=l+1;
    while(k<=j)
    {
    var temp2= arr[k-1];
          arr[k-1]=arr[k] ;
          arr[k]=temp2;
          k++;
          }
    
          arr[pivotCounter-1]=pivot;
    
    
    
    
    quickSort(arr,pivotCounter,u);
    quickSort(arr,0,pivotCounter-2);
    
    
    
    }
    
    0 讨论(0)
  • 2021-02-01 20:16

    You did not properly implement the base case termination, which causes quicksort to never stop recursing into itself with sublists of length 0.

    Change this:

    if (low < high)
        pivot_loc = partition(input, low, high);
    quicksort(input, low, pivot_loc - 1);
    quicksort(input, pivot_loc + 1, high);
    

    to this:

    if (low < high) {
        pivot_loc = partition(input, low, high);
        quicksort(input, low, pivot_loc - 1);
        quicksort(input, pivot_loc + 1, high);
    }
    
    0 讨论(0)
提交回复
热议问题