Insert Sort

#include #include #define MAXSIZE 20; typedef int KeyType; typedef struct { KeyType key; } RecordType; typedef struct { RecordType * r; int length; }SqList; void InitSqList(SqList &L); void AppendElement(SqList &L, KeyType key); void Display(SqList L); void InsertSort(SqList &L); void InitSqList(SqList &L) { int size = MAXSIZE + 1; L.r = (RecordType *)malloc(size * sizeof(RecordType)); L.length = 0; } void AppendElement(SqList &L, KeyType key) { int size = (int) MAXSIZE; if (L.length > size) { printf("%s", "list is full, can not append"); return; } L.length++; L.r[L.length].key = key; } void Display(SqList L) { register RecordType * p = &L.r[1]; while(p <= &L.r[L.length]) { printf("%d/t", p->key); p++; } } void InsertSort(SqList &L) { for (int i = 2; i <= L.length;i++) { if(L.r[i].key < L.r[i - 1].key) { L.r[0] = L.r[i]; L.r[i] = L.r[i - 1]; for (int j = i - 2; L.r[j].key > L.r[0].key; j--) { L.r[j + 1] = L.r[j]; } L.r[j + 1] = L.r[0]; } } } void main() { SqList L; InitSqList(L); AppendElement(L, 16); AppendElement(L, 13); AppendElement(L, 20); AppendElement(L, 18); AppendElement(L, 43); AppendElement(L, 21); AppendElement(L, 20); AppendElement(L, 91); AppendElement(L, 29); Display(L); printf("after insert sort"); InsertSort(L); Display(L); }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章