4.插入排序——表插入排序

本文針對表插入排序。
這種排序方法採用鏈表的數據結構,按順序放入數據,並按插入排序的原理修改next指針,這樣能夠做到排序時不移動數據。
排序完之後可以按next指向打印數據,也可以移動數據然後按數組下標打印數據。
它的時間複雜度仍是O(n的平方)。

 

 

程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#define MAXSIZE 50

typedef struct{
	int key;
	int other;
}node;

typedef struct
{
	node data;
	int next;
}lnode;

typedef struct
{
	lnode array[MAXSIZE];
	int length;
}list;


//將數組data中的數據依次放到靜態鏈表,並做插入排序,調整next指向的位置
void table_insert(list *l,node *data,int n)
{
	int i,higher,lower;
	
	l->array[0].data.key = INT_MAX;  //array[0]存放最大整數,不存放data數組的數據,所以實際數據量是length - 1
	l->array[0].next = 0;
	for(i = 0;i < n;i++){
		l->array[i + 1].data = data[i];
		lower = 0;
		higher = l->array[0].next;
		while(l->array[higher].data.key <= l->array[i + 1].data.key){  //找l->array[i + 1].data.key應該插入到的位置,用lower記錄應該插入位置的前一個位置,用higher記錄應該插入位置的後一個位置
			lower = higher;
			higher = l->array[higher].next;
		}
		l->array[i + 1].next = higher;  //修改next
		l->array[lower].next = i + 1;
	}
	l->length = n;
}

//根據next指向移動數據
void table_insertion_sort(list *l)
{
	int i,next,q;
	lnode t;
	
	next = l->array[0].next;  //next表示下一個需要移動的數據位置
	for(i = 1;i < l->length;++i){  //i之下是已經移動好的數據
		while(next < i)
			next = l->array[next].next;
		q = l->array[next].next; /* q指示尚未調整的表尾 */
		if(next != i){
			t = l->array[next];
			l->array[next] = l->array[i];
			l->array[i] = t;
			l->array[i].next = next;  //移走了原來的數據,那麼比其小的數據的next域將不再能指向它,所以爲了防止該值丟失,就用l->array[i]指向它,當以後那個比它小的數據指向它時,就用其指向位置的next所指向的位置替代,並用while循環確保其指向位置不在比i小的地方
		}
		next = q;
	}
}

//按next順序打印
void print_next(list *l)
{
	int i;
	lnode temp = l->array[l->array[0].next];
	for(i = 0;i < l->length;i++){
		printf("%d %d\t",temp.data.key,temp.data.other);
		temp = l->array[temp.next];
	}
	printf("\n");
}

//按靜態鏈表下標順序打印
void print_array(list *l)
{
	int i;
	for(i = 1;i <= l->length;i++)
		printf("%d %d\t",l->array[i].data.key,l->array[i].data.other);
}

//按數據大小獲取數組的next值放到adr數組
void sort(list *l,int *adr)  //adr數組下標表示第幾個小,值表示位置
{
	int i,p = l->array[0].next;
	for(i = 1;i <= l->length;i++){
		adr[i++] = p;
		p = l->array[p].next;
	}
}


void main()
{
	node data[10]={{5,6},{13,5},{22,2},{2,4},{6,5},{99,7},{6,15},{1,22},{15,12},{58,12}};
	list l;

	table_insert(&l,data,10);
	printf("befor sort:\n");
	print_array(&l);
	
	printf("\nprint by the 'next':\n");   
	print_next(&l);
	
	table_insertion_sort(&l);
	printf("print by sort:\n");
	print_array(&l);
	printf("\n");	
}


 

結果:

[19:21:31]# ./c
befor sort:
5 6     13 5    22 2    2 4     6 5     99 7    6 15    1 22    15 12   58 12
print by the 'next':
1 22    2 4     5 6     6 5     6 15    13 5    15 12   22 2    58 12   99 7
print by sort:
1 22    2 4     5 6     6 5     6 15    13 5    15 12   22 2    58 12   99 7


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章