Skip to content

Commit 18ba33b

Browse files
committed
Use binary search, close #1
1 parent adacfdf commit 18ba33b

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

sound.inc

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6945,14 +6945,26 @@ static const MainSound_SoundIDs[MAX_SOUNDS][MAINSOUND_E_SOUND] = {
69456945
*/
69466946
// native GetSoundInfo(soundid, speaker[], dialog[], slen, dlen); // Fake native
69476947
stock GetSoundInfo(soundid, speaker[], dialog[], slen, dlen) {
6948-
if(soundid >= MainSound_SoundIDs[0][MAINSOUND_SOUND_ID] && soundid <= MainSound_SoundIDs[MAX_SOUNDS - 1][MAINSOUND_SOUND_ID]) {
6949-
for(new sound = 0; sound < MAX_SOUNDS; sound++) {
6950-
if(soundid == MainSound_SoundIDs[sound][MAINSOUND_SOUND_ID]) {
6951-
strmid(speaker, MainSound_SoundIDs[sound][MAINSOUND_SOUND_SPEAKER], 0, slen, slen);
6952-
strmid(dialog, MainSound_SoundIDs[sound][MAINSOUND_SOUND_DIALOG], 0, dlen, dlen);
6953-
return 1;
6954-
}
6955-
}
6948+
new sound = MainSound_BinarySearch(soundid); // Since the array is already sorted, we can use a binary search
6949+
if(sound != -1) {
6950+
strmid(speaker, MainSound_SoundIDs[sound][MAINSOUND_SOUND_SPEAKER], 0, slen, slen);
6951+
strmid(dialog, MainSound_SoundIDs[sound][MAINSOUND_SOUND_DIALOG], 0, dlen, dlen);
6952+
return 1;
69566953
}
69576954
return 0;
6955+
}
6956+
6957+
// ========================================INTERNAL FUNCTIONS========================================
6958+
static MainSound_BinarySearch(soundid, start = 0, end = MAX_SOUNDS - 1) {
6959+
if(end >= start) {
6960+
new mid = start + (end - start) / 2;
6961+
if(MainSound_SoundIDs[mid][MAINSOUND_SOUND_ID] == soundid) {
6962+
return mid;
6963+
}
6964+
if(MainSound_SoundIDs[mid][MAINSOUND_SOUND_ID] > soundid) {
6965+
return MainSound_BinarySearch(soundid, start, mid - 1);
6966+
}
6967+
return MainSound_BinarySearch(soundid, mid + 1, end);
6968+
}
6969+
return -1;
69586970
}

0 commit comments

Comments
 (0)