954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to do Insertion Sort?

I've got an array BM[] with a length of 5. How would I declare my function in the heading and what am I doing wrong in my code, it keep giving me errors. Also I dont know how to apply it to my program to do the sorting. Like would I write cout<insertionSort(array BM[])
for i = 1 to length[BM]-1 do
{
value = BM[i]
j = i-1
while (j >= 0 && BM[j] > value)
{
BM[j + 1] = BM[j]
j = j-1
}
BM[j+1] = value
}

swbuko
Newbie Poster
12 posts since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

Try with something easy for start.

Sci@phy
Posting Whiz in Training
279 posts since Sep 2008
Reputation Points: 110
Solved Threads: 43
 
Try with something easy for start.

Well I have to do Insertion Sort or my program will run too slow; can you help me with learning how to do Insertion Sort?

swbuko
Newbie Poster
12 posts since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

Here's a good link from Narue on many sorts, including the Insertion Sort. Go about 1/3 of the way down to find the Insertion Sort segment. It's an efficient sort on data that's mostly sorted already, but not so great for random lists. Narue explains on the link. An array of length 5 is pretty small, so any sort will work well on it.

http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_sorting.aspx

This code:

insertionSort(array BM[])
for i = 1 to length[BM]-1 do
{
value = BM[i]
j = i-1
while (j >= 0 && BM[j] > value)
{
BM[j + 1] = BM[j]
j = j-1
}
BM[j+1] = value
}


isn't valid C++ code. You need brackets surrounding the function implementation, you need parentheses in your for-loop declaration, and you have a do and a while, but it isn't in the form of a do-while loop. Also, what is length ? I'm not sure what language this is.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

It looks like pseudocode.

You really want to translate this into C++ , write the whole program and see what you get.

stilllearning
Posting Whiz
309 posts since Oct 2007
Reputation Points: 161
Solved Threads: 43
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You