Insertion Sort

Was trying to come up with an algorithm for 'INSERTION SORT' based on the below description:
"The insertion sort splits an array into two sub-arrays. The first sub-array is sorted and increases in size as the sort continues. The second sub-array is unsorted, contains all the elements to yet be inserted into the first sub-array, and decreases in size as the sort continues. " - from mathbits.com

Just wanted to check if my take on it is correct. Below is a snippet from the code. ==> a[SIZE] is the array

for(int i=0;i<SIZE-1;i++) //inserts unsorted elements into sub-array.
{
for(int j=i+1;j>0;j--) // sub-array -- size grows incrementally.
{
if(a[j] > a[j-1]) //compares & swaps if not in the right order.
{
int h = a[j];
a[j] = a[j-1];
a[j-1] = h;
}
}
}
This is indeed an example of insertion sort, and it works fine too.
Just a couple of quick pointers - use code tags (the <> button in the format section) to better format your code - it makes your code more readable for the rest of us :D
1
2
3
4
5
6
7
8
9
10
11
12
for(int i=0;i<SIZE-1;i++) //inserts unsorted elements into sub-array.
{
    for(int j=i+1;j>0;j--) // sub-array -- size grows incrementally.
    { 
        if(a[j] > a[j-1]) //compares & swaps if not in the right order.
        {
            int h = a[j];
            a[j] = a[j-1];
            a[j-1] = h;
        }
    }
}

- Thank you!
- about the formatting - yes will make a note of it. As you can see it was my first post!
Topic archived. No new replies allowed.