排序的基本概念
排序(Sort)是将无序的记录序列(或称文件)调整成有序的序列。
直接插入排序
//插入排序法
int list_order(linklist H){
linklist p,q,r;
int t;
if(H == NULL){
printf("H is NULL");
return -1;
}
p = H->next;
H->next = NULL;
r = H;
while(p != NULL)
{
q = p;
p = p->next;
r = H;
while(r->next && r->next->data < q->data)
{
r = r->next;
}
q->next = r->next;
r->next = q;
}
return 0;
}
冒泡排序
//冒泡法
void sort_linklist(linklist H)
{
linklist P = NULL, Q = NULL;
datatype t = 0;
for(Q = H->next; Q!= NULL; Q = Q->next)
{
for(P = Q->next;P != NULL; P = P->next)
{
if( Q->data > P->data )
{
t = P->data;
P->data = Q->data;
Q->data = t;
}
}
}
}
快速排序
int partion(int *data,int low ,int hight);
int quick_sort(int *data,int low,int hight);
int main(int argc, const char* argv[]){
int data[]={2,6,7,8,3,5,9,4,1,0};
int i;
quick_sort(data,0,sizeof(data)/sizeof(int)-1);
for(i=0;i<sizeof(data)/sizeof(int);i++){
printf("%d ",data[i]);
}
puts("");
return 0;
}
int partion(int *data,int low ,int hight){
int temp = data[low];
int i;
//2,6,7,8,3,5,9,4,1,0
while(low<hight){
while(low<hight && temp <= data[hight]){
hight--;
}
data[low] = data[hight];
for(i=0;i<10;i++){
printf("%d ",data[i]);
}
printf("++++++low:%d,hight:%d\n",low,hight);
while(low<hight && temp >= data[low]){
low++;
}
data[hight] = data[low];
for(i=0;i<10;i++){
printf("%d ",data[i]);
}
printf("************low:%d,hight:%d\n",low,hight);
}
data[low] = temp;
puts("");
for(i=0;i<10;i++){
printf("%d ",data[i]);
}
printf("-------------------low:%d,hight:%d\n",low,hight);
return low;
}
int quick_sort(int *data,int low,int hight){
int t;
if(data == NULL){
return -1;
}
if(low >= hight){
return 0;
}
t = partion(data,low,hight);
//
quick_sort(data,low,t-1);
quick_sort(data,t+1,hight);
return 0;
}
简单选择排序
//简单选择排序
linklist list_range(linklist H){
linklist p,q,small;
data_t temp;
if (H == NULL){
printf("H is NULL\n");
return NULL;
}
for(p = H->next;p->next != NULL; p = p->next){
small = p;
for(q = p->next; q; q = q->next){
if(q->data < small->data){
small = q;
}
}
if(small != p){
temp = p->data;
p->data = small->data;
small->data = temp;
}
}
return H;
}