SortedCollection.st
changeset 4596 66a082fbc5b3
parent 3340 300d88cf8b14
child 5028 1f7e943ce46e
--- a/SortedCollection.st	Thu Aug 12 10:59:29 1999 +0200
+++ b/SortedCollection.st	Thu Aug 12 12:33:40 1999 +0200
@@ -640,6 +640,69 @@
      #(7 10 3 10 9 10 10 99) asSortedCollection before:9  
      #(7 10 3 10 9 10 10 99) asSortedCollection before:10   
     "
+!
+
+indexOf:anElement
+    "Return the index of anElement within the receiver. 
+     If the receiver does not contain anElement, return 0."
+
+    ^ self indexOf:anElement ifAbsent:0
+!
+
+indexOf:anElement ifAbsent:exceptionBlock
+    "Return the index of anElement within the receiver. 
+     If the receiver does not contain anElement, 
+     return the result of evaluating the argument, exceptionBlock."
+
+    |insertionIndex index "{ Class: SmallInteger }" 
+     obj|
+
+    firstIndex > lastIndex ifTrue:[
+        "/ empty
+        ^ exceptionBlock value
+    ].
+
+    "/ if I am small, the inherited linear search is faster ...
+    (lastIndex - firstIndex) < 20 ifTrue:[
+        ^ super indexOf:anElement ifAbsent:exceptionBlock
+    ].
+
+    insertionIndex := self indexForInserting:anElement.
+    insertionIndex > lastIndex ifTrue:[
+        insertionIndex := lastIndex
+    ] ifFalse:[
+        insertionIndex < firstIndex ifTrue:[
+            insertionIndex := firstIndex
+        ]
+    ].
+
+    index := insertionIndex.
+    [index >= firstIndex
+    and:[obj := contentsArray basicAt:index.
+            anElement = obj ifTrue: [^ index - firstIndex + 1].
+            [sortBlock value:anElement value:obj]]]
+                    whileTrue: [index := index - 1].
+
+    index := insertionIndex.
+    [index <= lastIndex
+    and: [obj := contentsArray basicAt: index.
+            anElement = obj ifTrue: [^ index - firstIndex + 1].
+            [sortBlock value:obj value:anElement]]]
+                    whileTrue: [index := index + 1].
+
+    ^exceptionBlock value
+
+    "
+     #('aa' 'bb' 'cc' 'dd') asSortedCollection indexOf:'bb'
+     #('aa' 'bb' 'cc' 'dd' 'aa' 'bb' 'cc' 'dd') asSortedCollection indexOf:'bb' 
+
+     |allSyms indices|
+     allSyms := Symbol allInstances asSortedCollection. 
+     Time millisecondsToRun:[
+         indices := allSyms collect:[:el | allSyms indexOf:el]. 
+     ].
+     indices = (1 to:allSyms size)
+    "
 ! !
 
 !SortedCollection methodsFor:'testing'!
@@ -695,6 +758,6 @@
 !SortedCollection class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic/SortedCollection.st,v 1.38 1998-03-13 16:24:04 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic/SortedCollection.st,v 1.39 1999-08-12 10:33:40 cg Exp $'
 ! !
 SortedCollection initialize!