By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,472 Members | 1,172 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,472 IT Pros & Developers. It's quick & easy.

sorting associative arrays

verbatim
P: 7
array is generated by user inputing a random word list that is then organized by word length:

[#] = length of each word in each array

if i have an array ordered as such:

Expand|Select|Wrap|Line Numbers
  1. wordList[9] = ["associate", "documents" ]
  2. wordList[5] = ["green", "about", "money" ]
  3. wordList[3] = ["dog", "cat", "top", "big", "vat" ]
  4. wordList[6] = ["floats" ]
  5.  
  6. how can i get these desired ordering results:
  7.  
  8. wordList[3] = ["dog", "cat", "top", "big", "vat" ]
  9. wordList[5] = ["green", "about", "money" ]
  10. wordList[6] = ["floats" ]
  11. wordList[9] = ["associate", "documents" ]
  12.  
  13. my first attempt to reorder, rendered the following:
  14.  
  15. wordList[9] = ["dog", "cat", "top", "big", "vat" ]
  16. wordList[5] = ["green", "about", "money" ]
  17. wordList[3] = ["floats" ]
  18. wordList[6] = ["associate", "documents" ]
  19.  
correctly re-ordered each array, but not the [#] associated with it.
Oct 28 '07 #1
Share this Question
Share on Google+
1 Reply


100+
P: 210
Expand|Select|Wrap|Line Numbers
  1. wordList[9] = ["associate", "documents" ]
  2. wordList[5] = ["green", "about", "money" ]
  3. wordList[3] = ["dog", "cat", "top", "big", "vat" ]
  4. wordList[6] = ["floats" ]
You are not using associative array syntax.
You have a partially-populated two dimensional subscripted array.
On the assumption that all unmentioned array elements are undefined, and also assuming that the strings in each sub array will all be of the same length, you can copy just the defined elements of wordList to a new array, sort the array using a suitable comparator, then overwrite just the defined elements of wordList with all the elements of the sorted temporary array.

I tried it with no problems.
Oct 29 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.