当前位置: 首页 > 科技观察

常用排序算法总结

时间:2023-03-18 22:38:31 科技观察

概述在计算机科学和数学中,排序算法(英文:Sortingalgorithm)是一种能够将一串数据按照特定的排序方式排列的算法。本文将总结几种常用的排序算法,包括冒泡排序、选择排序、插入排序、快速排序和归并排序,这些算法都是用Java代码实现的,并用图解简单介绍它们的实现原理。算法原理及实现1.冒泡排序示意图理解为通过反复遍历待排序列表,比较每对相邻的项,如果顺序错误则进行交换。JavaCodepublicclassBubbleSort{//logictosorttheelementspublicstaticvoidbubble_srt(intarray[]){intn=array.length;intk;for(intm=n;m>=0;m--){for(inti=0;iarray[k]){swapNumbers(i,k,array);}}printNumbers(array);}}privatestaticvoidswapNumbers(inti,intj,int[]array){inttemp;temp=array[i];array[i]=array[j];array[j]=temp;}privatestaticvoidprintNumbers(int[]input){for(inti=0;i0;j--){if(输入[j]<输入[j-1]){temp=输入[j];输入[j]=输入[j-1];输入[j-1]=temp;}}}returninput;}}4.QuickSortSchematicUnderstanding将原问题分解成几个与原问题规模较小但结构相似的子问题,解决这些子问题递归地。然后将这些子问题的解决方案组合成原始问题的解决方案。publicclassQuickSort{privateintarray[];privateintlength;publicvoidsort(int[]inputArr){if(inputArr==null||inputArr.length==0){return;}this.array=inputArr;length=inputArr.length;quickSort(0,length-1);}privatevoidquickSort(intlowerIndex,inthigherIndex){inti=lowerIndex;intj=higherIndex;//calculatepivotnumber,Iamtakingpivotasmiddleindexnumberintpivot=array[lowerIndex+(higherIndex-lowerIndex)/2];//分两数组同时(i<=j){/***在每次迭代中,我们将从左侧识别一个*大于枢轴值的数字,并且我们还将从右侧识别一个小于枢轴值的数字*。一旦搜索*完成,然后我们交换两个数字。*/while(array[i]pivot){j--;}if(i<=j){exchangeNumbers(i,j);//移动索引到extpositiononbothsidesi++;j--;}}//调用quickSort()方法递归if(lowerIndex

最新推荐
猜你喜欢