不使用sort方法对数组进行字母排序 [英] Alphabetical sorting of an array without using the sort method

查看:302
本文介绍了不使用sort方法对数组进行字母排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究Chris Pine的Ruby教程,目前正在研究一种不使用 sort 排序名称数组的方法。

I have been working through Chris Pine's tutorial for Ruby and am currently working on a way to sort an array of names without using sort.

我的代码如下。它可以完美运行,但比我想像的要进一步!

My code is below. It works perfectly but is a step further than I thought I had got!

puts "Please enter some names:"

name = gets.chomp

names = []

while name != ''

    names.push name

    name = gets.chomp

end

names.each_index do |first|
  names.each_index do |second|
        if names[first] < names[second]
            names[first], names[second] = names[second], names[first]
        end

  end
end

puts "The names you have entered in alphabetical order are: " + names.join(', ') 

排序是我遇到麻烦的地方。

It is the sorting that I am having trouble getting my head around.

我的理解是, each_index 将查看数组中每个项目的位置。然后 if 语句获取每个项目,如果数字大于下一个项目,它将在数组中交换该项目,继续执行直到最大的数字开始。我以为这只会颠倒我的数组,但是确实按字母顺序对其进行了排序。

My understanding of it is that each_index would look at the position of each item in the array. Then the if statement takes each item and if the number is larger than the next it swaps it in the array, continuing to do this until the biggest number is at the start. I would have thought that this would just have reversed my array, however it does sort it alphabetically.

有人可以通过这个算法按字母顺序工作以及在什么时候看起始字母是什么?

Would someone be able to talk me through how this algorithm is working alphabetically and at what point it is looking at what the starting letters are?

在此先感谢您的帮助。我敢肯定这是非常简单的事情,但经过大量搜索后我还是不太清楚!

Thanks in advance for your help. I'm sure it is something very straightforward but after much searching I can't quite figure it out!

推荐答案

我认为快速排序算法是较容易理解的算法之一:

I think the quick sort algorithm is one of the easier ones to understand:

def qsort arr
  return [] if arr.length == 0
  pivot = arr.shift
  less, more = arr.partition {|e| e < pivot }
  qsort(less) + [pivot] + qsort(more)
end

puts qsort(["George","Adam","Michael","Susan","Abigail"])

这个想法是选择一个元素(通常称为数据透视图) ,然后将数组划分为小于枢轴的元素和大于或等于枢轴的元素。然后对每个组进行递归排序,并与数据透视表结合。

The idea is that you pick an element (often called the pivot), and then partition the array into elements less than the pivot and those that are greater or equal to the pivot. Then recursively sort each group and combine with the pivot.

这篇关于不使用sort方法对数组进行字母排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆