Ordering process
To sort a set of data, e.g. [5] 2,3,1,4
- After the first round of sorting [2,3,1,4,5]
- After the second round of the sort [2,1,3,4,5]
- After the third round of the sort [1,2,3,4,5]
Bubble sort array
int flag=0,temp;
int s[10]={9,8,7,6,5,4,3,2,1,0}; //定义数组并赋值
for(int i=0;i<10;i++)
{
for(int j=0;j<10-i-1;j++)
{
if(s[j]>s[j+1]){
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
flag=1;
}
}
if(flag==0)
break;
}
The code number, the outer loop control cycle, the sequence is complete 10 cycles in the worst case; comparing the number of inner loop control; In Flag used to determine whether the exchange occurred, if no switching occurs, then the sort has been completed, then you do not need to cycle 10 times;
Bubble sort the list
The following is the code for the node is not the lead (i.e., a first node data field is not empty) list of
void swap(){
STUDENT *head_front ;
head_front=(STUDENT *)malloc(sizeof(STUDENT)); //为链表设置一个数据域为空的头节点
head_front->next=head;
STUDENT *t, *p,*q,*temp;
for(int i=0;i<sum+1;i++) //上面加了一个结点,所以这而是sum+1
{
int flag = 1;
t=head_front;
p=t->next;
q=p->next;
for(int j=0;j<sum-i-1;j++)
{
if(p->num > q->num)
{
t->next = q;
p->next = q->next;
q->next = p;
temp = p; p = q;q = temp;
flag = 0;
}
t = t->next;
p = t->next;
q = p->next;
}
if(flag)
break;
}
free(head_front); //排序完成后释放掉内存
}
The above code can only be achieved on a small element of the second list of elements than the sort studied for a long time, I do not know why, and so then I came back to find out the modification;
The complete code
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int num;
char name;
struct student *next;
}STUDENT;
STUDENT *head;
int sum;
void create(){
int num1;
char name1;
STUDENT *p_end=NULL,*p_new;
int i=0;
printf("请输入元素个数:");
scanf("%d",&sum);
for(int t=0;t<sum;t++)
{
printf("第%d个学生信息:",++i);
scanf("%d %c",&num1,&name1);
if(getchar()=='%')
break;
p_new=(STUDENT *)malloc(sizeof(STUDENT));
if(p_new==NULL)
exit(0);
if(i==1)
{
p_new->name=name1;
p_new->num=num1;
head=p_new;
p_end=p_new;
}
else
{
p_new->name=name1;
p_new->num=num1;
p_end->next=p_new;
p_new->next=NULL;
p_end=p_new;
}
}
}
void swap(){
STUDENT *head_front ;
head_front=(STUDENT *)malloc(sizeof(STUDENT));
head_front->next=head;
STUDENT *t, *p,*q,*temp;
for(int i=0;i<sum+1;i++)
{
int flag = 1;
t=head_front;
p=t->next;
q=p->next;
for(int j=0;j<sum-i-1;j++)
{
if(p->num > q->num)
{
t->next = q;
p->next = q->next;
q->next = p;
temp = p; p = q;q = temp;
flag = 0;
}
t = t->next;
p = t->next;
q = p->next;
}
if(flag)
break;
}
free(head_front);
}
void output()
{
STUDENT *p;
p=head;
for(int i=0;i<sum;i++)
{
printf("%d %c \n",p->num, p->name);
p=p->next;
}
printf("\n");
}
int main()
{
head=NULL;
create();
swap();
output();
}