赞
踩
这个不多做解释,比较简单,直接看图
也比较简单
思路如下图所示
如何来理解这个方法,我们举个例子来说明一下
给出一段数据为:3,44,38,5,47,15,36,26,27,2,46,4,19,50,48
目的:对它进行排序
代码如下:
- package aaa;
-
- public class ccc {
- public static void main(String[] args) {
- int []arr={3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
- int startIndex=-1;
- //第一步找到从哪个索引开始无序
- for (int i = 0; i < arr.length; i++) {
- if(arr[i]>arr[i+1]){
- startIndex=i+1;
- break;
- }
- }
- //下面段代码是重点,认真梳理一下还是比较好懂的
- for (int i = startIndex; i < arr.length; i++) {
- int j=i;
- while(j>0&&arr[j]<arr[j-1]){
- int temp=arr[j];
- arr[j]=arr[j-1];
- arr[j-1]=temp;
- j--;
- }
- }
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i]+" ");
- }
- }
- }

下图解析更加详细
首先引入递归这个概念这个之前学学过,反正就是函数反复调用本身不多加解释
注意递归函数一定要有出口,避免内存溢出,出口就是止提前终止程序的代码,和之前避免死循环的代码是类似的
快速排序的特点:快
思路如下图
我们还是举一个例子
给出一组数据为:6,1,2,7,9,3,4,5,10,8
利用快排进行排序的代码如下
-
- package aaa;
-
- public class ddd {
- public static void main(String[] args) {
- int []arr={6,1,2,7,9,3,4,5,10,8};
- quickSort(arr,0,arr.length-1);
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i]+" ");
- }
- }
- public static void quickSort(int[]arr,int i,int j){
- int start=i;
- int end=j;
- if(start>end)
- {
- return;
- }
- int baseNumber=arr[i];
- while(start!=end){
- //******注意一定要先end,再start****
- while(true){
- if(end<=start||(arr[end]<baseNumber)){
- break;
- }
- end--;
- }
- while(true){
- if(end<=start||(arr[start]>baseNumber)){
- break;
- }
- start++;
- }
- int temp=arr[start];
- arr[start]=arr[end];
- arr[end]=temp;
- }
- int temp=arr[i];
- arr[i]=arr[start];
- arr[start]=temp;
- quickSort(arr,i,start-1);
- quickSort(arr,start+1,j);
- }
- }
-
-

这里要注意:一定要先end再strat,至于为什么,自己可以试试先start再end,会出现什么错误
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。