冒泡排序
#include <stdio.h>
void bubble(int an[],int len);
void bubble(int an[],int len){
int i,j,t;
for(i = 0;i < len - 1;i++){
for(j = 0;j < len - i - 1;j++){
if(an[j] > an[j + 1]){
t = an[j];
an[j] = an[j + 1];
an[j + 1] = t;
}
}
}
}
int main(){
int an[] = {1,2,2,4,6,456,21,45,321,54};
int len = sizeof(an) / sizeof(an[0]);
bubble(an,len);
for(int i = 0;i < len;i++){
printf("%d ",an[i]);
}
return 0;
}
分治法:
#include <stdio.h>
void fenzhi(int an[],int left,int right){
int i,j,strand,temp;
strand = an[(left + right) / 2];
i = left;
j = right;
while (i <= j )
{
/* code */
while(an[i] < strand){
i++;
}
while(an[j] > strand){
j--;
}
if(i <= j){
temp = an[i];
an[i] = an[j];
an[j] = temp;
i++;
j--;
}
}
if(i < right){
fenzhi(an,i,right);
}
if(j > left){
fenzhi(an,left,j);
}
}
int main(){
int an[] = {1,1,245,345,21,5315,345,215,2,2,4};
int len = sizeof(an) / sizeof(an[0]);
fenzhi(an,0,len - 1);
for(int i = 0;i < len;i++){
printf("%d ",an[i]);
}
return 0;
}
链表的插入
//输入一串数字排序并删除其中的2
#include <stdio.h>
#include<stdlib.h>
struct stu{
int value;
struct stu *next;
};
void addlink(struct stu **p,int value);
void freelink(struct stu **p,int value);
void freelink(struct stu **p,int value);
void addlink(struct stu **p,int value){
struct stu *pre;
struct stu *now;
struct stu *new;
pre = NULL;
now = *p;
while(now != NULL && now->value < value){
pre = now;
now = now->next;
}
new = (struct stu *)malloc(sizeof(struct stu));
new->value = value;
new->next = now;
if(pre == NULL){
*p = new;
}
else{
pre->next = new;
}
}
void printlink(struct stu *p){
struct stu *new;
new = p;
while(new != NULL){
printf("%d ",new->value);
new = new->next;
}
putchar('\n');
}
void freelink(struct stu **p,int value){
struct stu *now;
struct stu *pre;
now = *p;
pre = NULL;
while(now != NULL && now->value != value){
pre = now;
now = now->next;
}
if(now == NULL){
printf("do not exist");
}
else
{
if(pre == NULL){
*p = now->next;
}
else{
pre->next = now->next;
}
}
free(now);
}
int main(){
struct stu *p;
int i;
p = NULL;
while (1)
{
/* code */
printf("please enter the num:");
scanf("%d",&i);
if(i == -1){
break;
}
addlink(&p,i);
printlink(p);
}
freelink(&p,2);
printlink(p);
return 0;
}