**强烈推荐学习进步的学习网站:**力扣 https://leetcode-cn.com/problemset/all/ 很多的题目都可以写
给定一个整数数组 nums,将该数组升序排列:
因为在力扣上的编辑器中 是通过固定的
public int[] sortArray(int[] nums) {
}
要返回一个数组,我在学习快速排序时写的都是直接通过一个静态方法直接就把整个排序后的数组通过 java的Arrays工具类直接就进行输出,现在就要把整个方法进行拆分。
1.力扣的本身的方法sortArray
2.自己编写的排序方法
3.把数组进行递归的方法
先是排序算法:
public int quickSort(int[] nums,int left,int height){
int i,j,t,temp;
i = left;
j = height;
temp = nums[left];
while(i != j){
// 先队尾 在队首
while(nums[j]>=temp && i<j){
j--;
}
while(nums[i]<=temp && i<j){
i++;
}
// 把 查出来的 小于基数与大于基数的值进行交换
if(i < j){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
nums[left] = nums[i];
nums[i] = temp;
return i; // 返回 I 开始我返回 temp 错误了 造成了溢出错误
}
第一步把基数进行交换后 小的数都在左边,大的都在右边 然后在进行排序
public int[] diGui(int[] nums,int left,int height){
if (nums.length<1 || left <0 || height >= nums.length || left >height){
return null;
}
// temp 就是 基数 也就是返回值 i
int temp = quickSort(nums,left,height);
if(temp > left){
// 这里从基数处进行 排序
diGui(nums,left,temp-1);
}
if(temp < height){
diGui(nums,temp+1,height);
}
// 返回数组
return nums;
}
最后一步基本的调用 然后完成
public int[] sortArray(int[] nums) {
int n = nums.length;
int[] arr = diGui(nums,0,n-1);
return arr;
}
总结:开始使用冒泡排序进行提交后会运行超时 所以才使用快速排序
在使用快速排序时也是一脸的懵逼,也是借鉴了其他同学的题解思路后才进行的一点改变。
还有很多的地方不懂 也是靠死记硬背写出来的,记下来也是对自己的鞭策吧。
推荐一个学习快速算法的博客:https://tryenough.com/arithmetic-quitsort