Quote (carteblanche @ Apr 13 2016 12:45am)
a single value given the key can be accessed in more or less O(1) time. (depending on how many collisions are in the hashtable, collision strategy, and whatnot)
Knew it was something like that.
Anyways if you're into OOP you can also convert your hash into class objects and then apply the sort on them:
Code
require "pp"
class HashObject
attr_reader :string, :int
def initialize(string, int)
@string = string
@int = int
end
end
def bubbleSort(objectsArray, toSort)
for i in 0..objectsArray.size
for j in i+1..objectsArray.size-1
objectsArray[i], objectsArray[j] = objectsArray[j], objectsArray[i] if(objectsArray[i].send(toSort) > objectsArray[j].send(toSort))
end
end
objectsArray
end
nameList = {"Joe"=>48, "Karen"=>17, "Abash"=>17, "Drake"=>1, "Will"=>23}
objectsArray = []
nameList.each do |key, value|
object = HashObject.new(key, value)
objectsArray.push object
end
pp objectsArray
puts
pp bubbleSort(objectsArray, "int")
Output:
Code
[#<HashObject:0x0000000328a0c0 @int=48, @string="Joe">,
#<HashObject:0x0000000328a098 @int=17, @string="Karen">,
#<HashObject:0x0000000328a070 @int=17, @string="Abash">,
#<HashObject:0x0000000328a048 @int=1, @string="Drake">,
#<HashObject:0x0000000328a020 @int=23, @string="Will">]
[#<HashObject:0x0000000328a048 @int=1, @string="Drake">,
#<HashObject:0x0000000328a070 @int=17, @string="Abash">,
#<HashObject:0x0000000328a098 @int=17, @string="Karen">,
#<HashObject:0x0000000328a020 @int=23, @string="Will">,
#<HashObject:0x0000000328a0c0 @int=48, @string="Joe">]
Understanding and implementing polymorphisism, metaprogramming, code guessing, what ever you want to call it is up to the implementer. Essentially you will have to determine all type pairs inside the hash, and then create objects to hold them then apply your custom sort to them.
There are many ways to solve this problem, none of them are going to be fast since it is entirely dependent on your sorting function.
Edit:: Also depending on language, strings may have to be sorted differently. In ruby the comparative operators work on strings as well resulting in me able to send the "string" toSort and the array of objects becomes sorted by the string parameter.
Code
irb(main):001:0> "a" > "b"
=> false
irb(main):002:0> "b" > "a"
=> true
If this were C you would have to implement specific sorting for all the different types you support and more underlying logic to pick the right one.
This post was edited by AbDuCt on Apr 12 2016 10:59pm