Thursday, July 30, 2009

How to keep an array sorted without applying any sorting algorithm?

Basically I have keep an array of 200 sorted by song titles, But I cannot use any sorting algorithms.





This is in C





any ideas please...thanks.......

How to keep an array sorted without applying any sorting algorithm?
Ok this is a little complex since you cant sort but here goes. You need to search the array using strcmp to find the first title that is greater then the title you are looking to place in the array. When you find it you then need to take that index and all the ones after it and move them up 1 index into the array, so say you need to insert at index 5, 5 becomes 6, 6 becomes 7 and so on. You need to do this for all elements that are valid after your index, so you will need to start moving the valid titles from the end of the array up 1 index and work your way back to the index you want to insert at. So 199-%26gt;200, 198-%26gt;199, 197-%26gt;198, 196-%26gt;197..... Only do this for valid titles in the array, if it is a null string then there is no need to move it on down. Then when removing from the array you do this in the reverse order.
Reply:Why can't you use sorting algos? Insertion sort should help you IMHO.





May be use hashing.
Reply:Sure, just iterate through the list on insertion to find where the new song title will go. Add an addition entry to the end (if necessary) and move everything down one space. Then insert the new song title.





Suppose you have 20 song titles in the array and the array is already dimensioned for 1000. Find where the song title goes, for example array element 15. Move 20 to 21, 19, to 20, etc. Then copy the new title into slot 15.
Reply:I think they are looking for a linked list.





If not, you just need to work backwards through the array, moving each element down one until you hit the point your new song title belongs.
Reply:The question seems to suggest that you are supposed to do an 'insert sort', which in fact is also a sorting algorithm. So I think the question itself is incorrect :)





Sample implementation of insert sort in C (you can find more with your favorite search engine): http://www.cs.uah.edu/~rcoleman/Sorting/...

easter cards

No comments:

Post a Comment