递归次数太多了,造成“栈溢出”,前来请教前辈们,应该怎么解决啊?
查看原帖
递归次数太多了,造成“栈溢出”,前来请教前辈们,应该怎么解决啊?
502305
CookieCookie楼主2022/3/30 20:55
import java.io.*;
public class Main {

	static int[] nums;
	static String s = "";
	static int n=0,i=0,j=0,hub=0;
	static String[] ss;

	public static void sort(int i , int j) {
		if(i<j) {
			int m = getHub(i,j);
			sort(i,m-1);
			sort(m+1,j);
		}
	}
	
	public static int getHub(int i,int j) {
		hub = nums[i];
		while(i!=j) {
			for(;j>=0;j--) {
				if(i==j) {
					nums[i] = hub ;
					break;
				}
				if(nums[j]<hub) {
					nums[i] = nums[j];
					break;
				}
			}
			
			for(;i<n;i++) {
				if(i==j) {
					nums[i] = hub ;
					break;
				}
				if(nums[i]>hub) {
					nums[j] = nums[i];
					break;
				}
			}
		}
		//每一趟返回HUB的最终位置,即I==J时,便于拆开数列。
		return i;
	}
	public static void main(String[] args) throws IOException{
		
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));

		s = bf.readLine();
		if(s!="") {
			 n = Integer.parseInt(s);
			 if(n>=1 && n<=100000) {
				 s = bf.readLine();
				 if(s!="") {
					 ss = s.split(" ");
					 if(ss.length==n) {
						 nums = new int[n];
						 for(i=0;i<n;i++) {
							 nums[i] = Integer.parseInt(ss[i]);
						 }
						sort(0,n-1);
						for(i=0;i<n;i++) {
							pw.print(nums[i]+" ");	
						}
						
						pw.close();
					 }
						
				}
			 }
		}
	}

}

2022/3/30 20:55
加载中...