c++insertion-sort

C++ insertion sort


I have this function called WordSort(worddata W [], int count) that is fed two variables 1 - worddata is the array holding information on a given word in a file. count is just the counter variable to see which word in the array we are looking at.

the words.txt file that is read into this program would just be a string of words.

this is a list of words
there are letters and numbers
23 people recommend this program.

Heres the function:

void WordSort (worddata W [], int count)
{
  for (int i=1; i < count; i++)
         {
           for (int j=i; j > 0 && W[j-1].word > W[j].word; j--)
             {
               Swap(W[j], W[j-1]);
             }
         }
}

The swap function is suppose to swap every element with the one before it as long as j > 0 or the list is over. Im confused on how to complete the swap function, here's the example i was given.

void Swap (worddata & a, worddata & b)
{
 int += a;
 a = b;
 b =+;
}

Swap is suppose to swap every element with the one before it

I think the WordSort function works fine, the only thing missing is the Swap function. Could anyone point me in the right direction or explain insertion sorting better to me?


Solution

  • Swap should look like this -- I have no idea how your example is even close.

    void Swap (worddata & a, worddata & b)
    {
     worddata temp = a;
     a = b;
     b = temp;
    }