实现快速排序算法

编程入门 行业动态 更新时间:2024-10-26 20:30:50
本文介绍了实现快速排序算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现快速排序算法从这本书

I found quicksort algorithm from this book

这是算法

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

和我做了这个C#code:

And I made this c# code:

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] + " "; } }

当我这样调用函数快速排序(ARR,0,arr.Length-1); 我得到这个错误类型的未处理的异常System.StackOverflowException发生将它传递空数组......当这样的快速排序(ARR,0,arr.Length)通话功能; 我得到错误索引是该数组的边界之外在这一行 INT支点=输入[高]; 但是数组顺利通过。

When I call function like this quicksort(arr,0,arr.Length-1); I get this error An unhandled exception of type 'System.StackOverflowException' occurred it 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.

我也想打印它像这样打印(输入,tbQuick); ,但在何处放置它,所以它会打印时,快速排序完成

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

推荐答案

您没有正确实施基本情况终止,这将导致快速排序永远不要停止递归到本身长度为0的子列表。

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

更改此:

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

这样:

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

更多推荐

实现快速排序算法

本文发布于:2023-11-29 01:06:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!