sorting - insert sort

#include "stdio.h"
#include "string.h"

#define MAX_LIST 50


typedef struct _SqList {
    int data[MAX_LIST];
    int length;
}SqList;

void swap( SqList* L,  unsigned index1, unsigned index2 )
{
    if( index1 >= L->length || index2 >= L->length ) return;

    if( index1 == index2 ) return;

    L->data[index1] = L->data[index1] ^ L->data[index2];

    L->data[index2] = L->data[index1] ^ L->data[index2];

    L->data[index1] = L->data[index1] ^ L->data[index2];
}

//insert sort continuously inserts one element into a sorted array
//shifts elements sequentially to the right one by one until a proper
//position is secured for the new element
void InsertSort(SqList* L)
{   
    int i, j, temp; 
    for( i = 1;  i < L->length; i++ )
    {
        temp = L->data[i];
        for( j = i - 1; j >-1 && temp < L->data[j]; j-- )
        {
            L->data[j+1] = L->data[j];
        }
        L->data[j+1] = temp;
    }
}

int main()
{
    SqList d;
    int intarr[] = {1,10,23,48,65,31,-21,9,88,100};
    memcpy( d.data, intarr, sizeof(intarr));
    d.length = sizeof(intarr)/sizeof(int);  
    int index = 0;
    printf("Original array:\n");
    for( ; index < d.length; index++ )
        printf(" %d", d.data[index] );
    printf("\nSelect sort...\n");
    InsertSort( &d );
    for( index = 0; index < d.length; index++ )
        printf(" %d", d.data[index] );
    printf("\n");
    return 0;
}

你可能感兴趣的:(sorting - insert sort)