Java基础巩固——排序
快速排序
基本思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对两部分继续进行排序,直到整个序列有序。
实例:
1.一趟排序的过程:
2.排序的全过程:
把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比他小,则交换,比它大不做任何处理;
交换了以后再和小的那端比,比它小不交换,比它大交换。这样循环往复,一趟排序完成,左边的就是比中轴小的,
右边的就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | public class QucikSortDemo { public static void main(String arg[]) { int [] numbers = { 10 , 89 , 87 , 76 , 56 , 46 , 11 , 75 , 32 , 35 , 98 }; System.out.println( "排序前:" ); printArr(numbers); quickSort(numbers); System.out.println( "排序后:" ); printArr(numbers); } /** * 查找出中轴位置(默认是最低为low)的在number数组排序后所在位置 * * @param numbers * @param low * @param high * @return */ public static int getMiddle( int [] numbers, int low, int high) { // 数组的第一位作为中轴 int temp = numbers[low]; while (low < high) { while (low < high && numbers[high] > temp) { high--; } // 比中轴晓得记录移动到低端 numbers[low] = numbers[high]; while (low < high && numbers[low] < temp) { low++; } // 比中轴大的记录移到高端 numbers[high] = numbers[low]; } // 中轴记录到尾 numbers[low] = temp; // 返回中轴的位置 return low; } /** * 分治排序 * * @param numbers * @param low * @param high */ public static void quickSort( int [] numbers, int low, int high) { if (low < high) { // 将numbers数组进行一分为二 int middle = getMiddle(numbers, low, high); // 将低字段表进行递归排序 quickSort(numbers, low, middle - 1 ); // 将高字段表进行递归排序 quickSort(numbers, middle + 1 , high); } } public static void quickSort( int [] numbers) { if (numbers.length > 0 ) { quickSort(numbers, 0 , numbers.length - 1 ); } } public static void printArr( int [] numbers) { for ( int i = 0 ; i < numbers.length; i++) { System.out.print(numbers[i] + "," ); } System.out.println( "" ); } } |
个人博客网站 http://www.janti.cn
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)