//链表形式的直接插入排序
#include<stdio.h>
#include<stdlib.h>
typedef int T;
typedef struct node {
T element;
struct node* Link;
}Node;
typedef struct list {
Node* First;
}List;
Node* NewNode(T x) {
Node* n = (Node*)malloc(sizeof(Node));
n->element = x;
n->Link = NULL;
return n;
}
void InsertSort(List * lst) {
Node* unsorted, * sorted, * p, * q;
if (lst->First != NULL)
{
sorted = lst->First;
while (sorted->Link !=NULL )
{
unsorted = sorted->Link;
if (unsorted->element < lst->First->element)
{
sorted->Link = unsorted->Link;
unsorted->Link = lst->First;
lst->First = unsorted;
}
else {
while (unsorted->element > sorted->element)
{
sorted = sorted->Link;
unsorted = unsorted->Link;
}
//再从头比较一次
q = lst->First;
p = q;
while (unsorted->element > q->element)
{
p = q;
q = q->Link;
}
sorted->Link = unsorted->Link;
if (q==lst->First) {
unsorted->Link =lst->First;
lst->First = unsorted;
}
else {
p->Link = unsorted;
unsorted->Link = q;
}
}
}
}
}
void CreateList(List* lst, T headElem) {
lst->First= NewNode(headElem);
}
void AddNode(List* lst, T elem) {
Node* temp = NewNode(elem);
Node* rear;
rear = lst->First;
for (; rear->Link; rear = rear->Link);
rear->Link = temp;
}
void PrintList(List* lst) {
Node* rear;
rear = lst->First;
for (; rear; rear = rear->Link) {
printf("%-6d ", rear->element);
}
printf("\n");
}
void main() {
List* lst = (List*)malloc(sizeof(List));
CreateList(lst, -12);
AddNode(lst, 1);
AddNode(lst, 100);
AddNode(lst, -88);
AddNode(lst, -9999);
AddNode(lst, 222);
AddNode(lst, 0);
AddNode(lst, -3);
AddNode(lst, -5);
AddNode(lst, -5);
AddNode(lst, -5);
AddNode(lst, -5);
AddNode(lst, -55555);
PrintList(lst);
InsertSort(lst);
PrintList(lst);
}
result:
-12 1 100 -88 -9999 222 0 -3 -5 -5 -5 -5 -55555
-55555 -9999 -88 -12 -5 -5 -5 -5 -3 0 1 100 222
//顺序表上的直接插入排序
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef int T;
typedef struct list {
int size;
T elements[MAXSIZE];
}List;
void InsertSort(List *lst) {
int i, j; T x;
for (i = 1; i < lst->size; i++)
{
x = lst->elements[i];
for ( j= i-1; j >=0 && x<lst->elements[j]; j--)
{
lst->elements[j + 1] = lst->elements[j];
}
lst->elements[j + 1] = x;
}
}
void main() {
int i;
List* lst = (List*)malloc(sizeof(List));
lst->size = 9;
//lst->elements
lst->elements[0]=9;
lst->elements[1]=8;
lst->elements[2]=7;
lst->elements[3]=6;
lst->elements[4]=5;
lst->elements[5]=4;
lst->elements[6]=3;
lst->elements[7]=2;
lst->elements[8]=1;
InsertSort(lst);
//memcpy(lst->elements, temp, 10);
for (i = 0; i < 9; i++)
{
printf("%d \n", lst->elements[i]);
}
}
result:
1
2
3
4
5
6
7
8
9