C--冒泡排序和插入排序

1-插入排序
1
#include "stdio.h" 2 3 #define N 6 4 5 void swap(int *a,int *b); 6 void InsertSort(int a[],int n); 7 8 9 int main() 10 { 11 int a[N]; 12 for(int i=0;i<N;i++) 13 scanf("%d",&a[i]); 14 15 InsertSort(a,N); 16 17 for(int i=0;i<N;i++) 18 printf("%d ",a[i]); 19 return 0; 20 } 21 22 void InsertSort(int a[],int n) 23 { 24 int x; 25 for(int i=1;i<n;i++) 26 {//i是有序区范围,j是有序区的最后一个元素下标 27 28 x=a[i]; 29 int j=i-1; 30 while(j>=0&&x<a[j]) 31 { 32 a[j+1]=a[j];//向后挪一个位置 33 j--; 34 } 35 a[j+1]=x; 36 } 37 38 }

2-冒泡

 1 #include "stdio.h"
 2 
 3 #define N 6
 4 
 5 void swap(int *a,int *b);
 6 
 7 //常规的冒泡
 8 void BubbleSort(int a[],int n);
 9 //若某轮无swap发生,则已经有序
10 void BubbleSort_1(int a[],int n);
11 //若某部分已经有序,则下一轮无需考虑
12 void BubbleSort_2(int a[],int n);
13 
14 int main()
15 {
16     int a[N];
17     for(int i=0;i<N;i++)
18         scanf("%d",&a[i]);
19 
20     BubbleSort(a,N);
21 
22     for(int i=0;i<N;i++)
23         printf("%d ",a[i]);
24     return 0;
25 }
26 
27 //常规的冒泡
28 void BubbleSort(int a[],int n)
29 {
30     int i,j,t;
31     for(i=1;i<n;i++)
32     {//控制轮数 n-1轮
33         for(j=0;j<=n-1-i;j++)
34         {//每一轮中相邻两个比较,
35             if(a[j]>a[j+1])
36                 swap(&a[j],&a[j+1]);
37         }
38     }
39 }
40 
41 void swap(int *a,int *b)
42 {
43     int t;
44     t=*a;
45     *a=*b;
46     *b=t;
47 }
48 
49 //若某轮无swap发生,则已经有序
50 void BubbleSort_1(int a[],int n)
51 {
52     //设置一个是否发生交换标志
53     int swap_flag = 1   //交换
54     for(int i=1;i<n&&swap_flag;i++)
55     {
56         swap_flag=0;
57         for(int j=0;j<n-i-1;j++)
58         {
59             if(a[j]<a[j+1])
60             {
61                 swap(&a[j],&a[j+1]);
62                 swap_flag=1;
63             }
64 
65         }
66     }
67 }
68 
69 //若某部分已经有序,则下一轮无需考虑
70 void BubbleSort_2(int a[],int n)
71 {
72     //设置一个记录最后一次交换时两个数中前一个数的下标
73     int last_swap_index =n-1;
74     for(int i=1;last_swap_index>0;i++)
75     {
76         int temp = -1;//临时存放下标
77         for(int j=0;j<last_swap_index;j++)
78         {
79             if(a[j]<a[j+1])
80             {
81                 swap(&a[j],&a[j+1]);
82                 temp=j;
83             }
84 
85         }
86         last_swap_index=temp;
87     }
88 }

 

posted @ 2020-03-31 11:14  亚斯娜  阅读(210)  评论(0)    收藏  举报