冒泡排序、二分查找、单向链表操作

#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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值