#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int a[] = {11,2,3,44,58,16,7,8,9,10};
//int a[] = {11,2,3,4,5,6,7,8,9,10};
//冒泡排序
int bubble_sort(int a[],int n)
{
int i,j;
int tmp;
for(i=0;i<n-1;i++)//轮数
{
//优化:两两比较如果没有发生交换(已经是有序序列),则flag=0不变,否则flag=1
int flag = 0;
for(j=0;j<n-1-i;j++)//每轮需要比较的次数
{
if(a[j] > a[j+1])
{
tmp = a[j+1];
a[j+1] = a[j];
a[j] = tmp;
flag = 1;
}
}
//printf("i=%d",i);
if(flag == 0)
break;
}
printf("a[] = ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
//二分查找
int binary_search(int obj)
{
int min=0,mid,max=sizeof(a)/sizeof(int)-1;
while(min<=max) {
mid = (min+max)/2;
if(a[mid]==obj) {
printf("a[%d] = %d\n",mid,obj);
return;
}
else if(a[mid]<obj) min = mid+1;
else max = mid-1;
}
printf("cannot find %d!\n",obj);
}
struct node {
int a;
struct node *next;
};
//打印链表
void print_list(struct node *p)
{
while(p)
{
printf("%d",p->a);
p = p->next;
}
printf("\n");
}
//创建链表
struct node* create_list(int size)
{
int i;
struct node *head = malloc(sizeof(struct node));
head->a = 0;
head->next = NULL;
struct node *p = head;
for(i=1;i<size;i++)
{
struct node *tmp= malloc(sizeof(struct node));
tmp->a = i;
tmp->next = NULL;
p->next = tmp;
p = tmp;
}
return head;
}
//释放链表
void drop_list(struct node *p)
{
while(p)
{
struct node *tmp = p->next;
free(p);p = tmp;
}
}
//反转链表
struct node* reserve_list(struct node *p)
{
struct node *pre = NULL;
struct node *tmp = NULL;
//empty list
if(p==NULL)
return NULL;
//only one node
if(p->next==NULL)
return p;
while(p)
{
tmp = p->next;//save the next node of 'p'
p->next = pre;//change the next node to the previous node
//reset 'pre' and 'p'
pre = p;
p = tmp;
}
return pre;
}
int main()
{
bubble_sort(a,sizeof(a)/sizeof(int));
binary_search(3);
binary_search(99);
struct node *head;
head = create_list(10);
print_list(head);
head = reserve_list(head);
print_list(head);
drop_list(head);
}
[xiongli@localhost workspace]$ ./a.out
a[] = 2 3 7 8 9 10 11 16 44 58
a[1] = 3
cannot find 99!
0123456789
9876543210