Content

Ruby实现插入排序算法及进阶的二路插入排序代码示例(ruby 数组操作)满满干货

文章摘要

这篇文章介绍了一种名为“two-way sort”的自定义排序算法。该算法通过以下步骤对输入数据进行排序: 1. 初始化两个指针`first`和`final`,以及一个临时数组`temp`。将输入数据的第一个元素复制到`temp[0]`中。 2. 从第二个元素开始遍历输入数据,根据当前元素与`temp`数组中特定位置的值进行比较: - 如果当前元素大于等于`temp[final]`,则将元素插入到`temp`数组的末尾。 - 如果当前元素小于等于`temp[first]`,则将元素插入到`temp`数组的开头,并调整`first`指针。 - 如果当前元素介于`temp[first]`和`temp[final]`之间,则通过插值方法找到合适的位置插入。 3. 插值插入时,使用二分查找确定插入位置,并通过移位操作将已排序的部分逐步合并到`temp`数组中。 4. 最终,将排序后的`temp`数组分为两部分,分别为有序区和无序区,输出结果。 该算法通过分阶段插入和调整元素位置,实现一种插值排序的方式。代码中包含插值、交换和移位操作,整体逻辑较为复杂。

 def two_way_sort data first,final=0,0 temp=[] temp[0]=data[0] result=[] len=data.length for i in 1..(len-1) if data[i]>=temp[final] final +=1 temp[final]=data[i] elsif data[i]<=temp[first] first=(first -1 + len)%len temp[first]=data[i] else if data[i]<temp[0] low=first high=len -1 while low <=high do m=(low + high)>>1 if data[i]>temp[m] low=m + 1 else high=m -1 end end j=first – 1 first -=1 while j < high do temp[j]=temp[j+1] j +=1 end temp[high]=data[i] else low=0 high=final while low <=high do m=(low + high)>>1 if data[i]>=temp[m] low=m + 1 else high=m – 1 end end j=final + 1 final +=1 while j > low do temp[j]=temp[j-1] j -=1 end temp[low]=data[i] end end p temp end i=0 for j in first..(len – 1) result[i]=temp[j] i +=1 end for j in 0..final result[i]=temp[j] i +=1 end return result end data=[4,1,5,6,7,2,9,3,8].shuffle p data result=two_way_sort data p result