# c - 排序 - 在C中，冒泡排序

``````
#include<stdio.h>

int main()

{

int n, i, j, a[5], b, temp;

printf("Enter the number of elements to be sortedn");

scanf("%d", &n);

for(i = 0; i < n; ++i)

{

printf("%d - Enter the elements - ", i);

scanf("%d", &a[i]);

}

for(i = 0; i < n; ++i)

{

for(j = 0; j < n+1; ++j)

{

if(a[i] > a[i+1])

{

temp = a[i];

a[i] = a[i+1];

a[i+1] = temp;

}

}

}

for (i = 0; i < n; ++i)

{

printf("%dn", a[i]);

}

return 0;

}

``````

``` ```
2

12

1

13

``` ```

``` ```
2

1

12

13

``` ```

``````
#include<stdio.h>

int main()

{

int n, i, j, a[5], b, temp;

printf("Enter the number of elements to be sortedn");

scanf("%d", &n);

for(i = 0; i < n; ++i)

{

printf("%d - Enter the elements - ", i);

scanf("%d", &a[i]);

}

for(i = 0; i < n; i++)

{

for(j = 0; j < n-1; j++)

{

if(a[j] > a[j+1])

{

temp = a[j];

a[j] = a[j+1];

a[j+1] = temp;

}

}

}

for (i = 0; i < n; ++i)

{

printf("%dn", a[i]);

}

return 0;

}

``````
``````
/*By your approach , in inner loop you are not checking the each elements . So change i to j in swapping , and limit of j should be till n-1*/

#include<stdio.h>

int main()

{

int n, i, j, a[10], b, temp=0;

printf("Enter the number of elements to be sortedn");

scanf("%d", &n);

for(i = 0; i < n; ++i)

{

printf("%d - Enter the elements - ", i);

scanf("%d", &a[i]);

}

for(i = 0; i < n; ++i)

{

for(j = 0; j < n-1; ++j) // notice limit , also complexity can be reduced by changing to(j<n-i-1)

{

if(a[j] > a[j+1])

{

temp = a[j]; // changed variable

a[j] = a[j+1];

a[j+1] = temp;

}

}

}

for (i = 0; i < n; ++i)

{

printf("%dn", a[i]);

}

return 0;

}

``````
``````
#include<stdio.h>

int main()

{

int n, i, j, a[5], b, temp;

printf("Enter the number of elements to be sortedn");

scanf("%d", &n);

for(i = 0; i < n; ++i)

{

printf("%d - Enter the elements - ", i);

scanf("%d", &a[i]);

}

for(i = 0; i < n; ++i)

{

for(j = 0; j < n; ++j)

{

if(a[j] > a[j+1]) //change the varible instead of i to j

{

temp = a[j];

a[j] = a[j+1];

a[j+1] = temp;

}

}

}

for (i = 0; i < n; ++i)

{

printf("%dn", a[i]);

}

return 0;

}

``````
``````

#include<stdio.h>

void bubble_sort(int a[],int n);

void bubble_sort(int a[],int n)

{

int i,j;

int temp;

for(i=0;i<n;i++)

{

for (j=0; j<=n-i-1;j++)

{

if (a[j]>a[j+1])

{

temp = a[j];

a[j] = a[j+1];

a[j+1] = temp;

}

}

}

}

main()

{

int a[10];

int i,n;

printf("Enter the numbern");

scanf("%d",&n);

printf("Enter the numbern");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

bubble_sort(a,n);

printf("sorted elements aren");

for(i=0;i<n;i++)

printf("%dn",a[i]);

}

``````