java - 自定义快速排序在 java 中不起作用
问题描述
我已经实现QuickSort
了,但是由于某些奇怪的原因,我的代码给出了 StackOverflow 异常。我一直在努力理解为什么我的代码会破坏任何想法,为什么我的代码会被破坏?还有其他方法可以优化吗?递归导致我的堆栈溢出;但不能放在发生这种情况的地方!
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void quickSort(int[] arr,int low,int high) {
// Complete this function
int p =partition(arr,low,high);
System.out.println("partiion at p[]"+p);
if(low<p){
System.out.println("starging quickSort at low[]"+low+" hgh["+(p-1));
quickSort(arr,low,p-1);
}
if(p<high){
System.out.println("starging quickSort at low[]"+p+1+" hgh["+high);
quickSort(arr,p+1,high);
}
}
static void swap(int []a,int x,int y){
int tmp = a[y];
a[y]=a[x];
a[x]=tmp;
}
static int partition(int[] arr,int low,int high){
int pivot = arr [low+ (high-low)/2];
int left = low;
int right = high;
System.out.println("pivot["+pivot+"] left ["+left+"]right["+right+"]");
while(left<= right)
{
while(arr[left] < pivot){
left++;
}
System.out.println("**..done now left ["+left+"]");
while(arr[right] >pivot){
right--;
}
System.out.println("##..done now right ["+right+"]");
if(left <=right){
swap(arr,left,right);
right--;
left++;
}
System.out.println("#swapping");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + (i != arr.length - 1 ? " " : ""));
}
System.out.println("done#swapping");
}
return left;
}
static int[] quickSort(int[] arr) {
quickSort(arr,0,arr.length-1);
return arr;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
System.out.println("ubsoted ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + (i != arr.length - 1 ? " " : ""));
}
System.out.println("");
int[] result = quickSort(arr);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println("");
in.close();
}
}
解决方案
您没有指定返回语句,这就是递归调用快速排序时堆栈溢出的原因。
因此,在快速排序方法中添加这样的返回条件作为第一条语句。
static void quickSort(int[] arr,int low,int high) {
if (high <=low) {
return;
}
推荐阅读
- html - VS Code 扩展以纠正 html 自动关闭标签烦人的行为
- corosync - Corosync 仅显示一个节点
- git - 将 Node-red 流自动推送到 Gitlab
- mysql - 在MySQL中如何检查一个数字是否在一系列范围的数字范围之间
- amazon-web-services - Amazon SNS 继续发送带有最后一个字符串的消息
- tensorflow - Tensorboard Profiler 错误无法加载动态库“libcupti.so.11.2”
- python - 派生记录器中的 LogRecord 属性
- javascript - Google 时间线 Chartwrapper 和 Controlwrapper
- python - 使用 Tkinter 的 Python 视频播放器
- java - Java PrinterJob调用job.print的速度