C# 实现快速排序算法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13648252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:20:17  来源:igfitidea点击:

Implementing quicksort algorithm

c#algorithmquicksort

提问by a1204773

I found quicksort algorithm from this book

我从这本书中找到了快速排序算法

This is the algorithm

这是算法

QUICKSORT (A, p, r)
if p < r
    q = PARTITION(A, p, r)
    QUICKSORT(A, p, q-1)
    QUICKSORT(A, q+1, r)

PARTITION(A, p, r)
x=A[r]
i=p-1
for j = p to r - 1
  if A <= x
     i = i + 1
     exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i + 1

And I made this c# code:

我做了这个 c# 代码:

private void quicksort(int[] input, int low, int high)
{
    int pivot_loc = 0;

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

private int partition(int[] input, int low, int high)
{
    int pivot = input[high];
    int i = low - 1;

    for (int j = low; j < high-1; j++)
    {
        if (input[j] <= pivot)
        {
            i++;
            swap(input, i, j);
        }
    }
    swap(input, i + 1, high);
    return i + 1;
}



private void swap(int[] ar, int a, int b)
{
    temp = ar[a];
    ar[a] = ar[b];
    ar[b] = temp;
}

private void print(int[] output, TextBox tbOutput)
{
    tbOutput.Clear();
    for (int a = 0; a < output.Length; a++)
    {
        tbOutput.Text += output[a] + " ";
    }
}

When I call function like this quicksort(arr,0,arr.Length-1);I get this error An unhandled exception of type 'System.StackOverflowException' occurredit pass empty array... when call function like this quicksort(arr,0,arr.Length);I get error Index was outside the bounds of the array.on this line int pivot = input[high];but array passed successfully.

当我打电话功能这样quicksort(arr,0,arr.Length-1);我得到这个错误An unhandled exception of type 'System.StackOverflowException' occurred把它传给空数组......当这样的呼叫功能quicksort(arr,0,arr.Length);我得到的错误Index was outside the bounds of the array.在这条线int pivot = input[high];,但阵顺利通过。

I also want to print it like this print(input,tbQuick);but where to place it so it would print when quicksort finished?

我也想像这样打印它,print(input,tbQuick);但是把它放在哪里,以便在快速排序完成时打印?

采纳答案by Deestan

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

您没有正确实现基本情况终止,这导致quicksort永远不会停止使用长度为 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);
}

回答by Eren Ers?nmez

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

除了 Deestan 的回答,你还有这个错误:

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

It should be:

它应该是:

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

回答by FBryant87

Just in case you want some shorter code for Quicksort:

以防万一您想要一些更短的 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.

当然,使用任何合适的方法获取 p (pivot)。

回答by Bharathkumar V

A Simple Quick Sort Implementation.

一个简单的快速排序实现。

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

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();
*/

回答by zishan shaikh

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);



}

回答by Ali Bayat

This is the shortest implementation of Quick Sort algorithm (Without StackOverflowException)

这是快速排序算法的最短实现(无StackOverflowException

IEnumerable<T> QuickSort<T>(IEnumerable<T> i) where T :IComparable
{
    if (!i.Any()) return i;
    var p = i.ElementAt(new Random().Next(0, i.Count() - 1));
    return QuickSort(i.Where(x => x.CompareTo(p) < 0)).Concat(i.Where(x => x.CompareTo(p) == 0)).Concat(QuickSort(i.Where(x => x.CompareTo(p) > 0)));
}

回答by Arun Kumar

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

QuickSort 的简单通用 C# 实现,可以使用第一个或最后一个值或任何其他中间值作为数据透视表

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

-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

A,和,猫,聪明,快,在这里,是,真的

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.phpand 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.

这里要注意的一件重要事情是,这段经过优化且简单的代码可以正确处理重复项。我尝试了几个发布的快速排序代码。那些没有为此(整数数组)输入提供正确结果或只是挂起,例如https://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise -9.phphttp://www.softwareandfinance.com/CSharp/QuickSort_Iterative.html。因此,如果作者还想使用处理重复的代码,这将是一个很好的参考。