1/* Bubble sort code in C */
2#include <stdio.h>
3
4int main()
5{
6 int array[100], n, c, d, swap;
7
8 printf("Enter number of elements\n");
9 scanf("%d", &n);
10
11 printf("Enter %d integers\n", n);
12
13 for (c = 0; c < n; c++)
14 scanf("%d", &array[c]);
15
16 for (c = 0 ; c < n - 1; c++)
17 {
18 for (d = 0 ; d < n - c - 1; d++)
19 {
20 if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
21 {
22 swap = array[d];
23 array[d] = array[d+1];
24 array[d+1] = swap;
25 }
26 }
27 }
28
29 printf("Sorted list in ascending order:\n");
30
31 for (c = 0; c < n; c++)
32 printf("%d\n", array[c]);
33
34 return 0;
35}
36
37
1#include <bits/stdc++.h>
2using namespace std;
3
4void swap(int *xp, int *yp)
5{
6 int temp = *xp;
7 *xp = *yp;
8 *yp = temp;
9}
10
11// A function to implement bubble sort
12void bubbleSort(int arr[], int n)
13{
14 int i, j;
15 for (i = 0; i < n-1; i++)
16
17 // Last i elements are already in place
18 for (j = 0; j < n-i-1; j++)
19 if (arr[j] > arr[j+1])
20 swap(&arr[j], &arr[j+1]);
21}
22
23/* Function to print an array */
24void printArray(int arr[], int size)
25{
26 int i;
27 for (i = 0; i < size; i++)
28 cout << arr[i] << " ";
29 cout << endl;
30}
31
32// Driver code
33int main()
34{
35 int arr[] = {64, 34, 25, 12, 22, 11, 90};
36 int n = sizeof(arr)/sizeof(arr[0]);
37 bubbleSort(arr, n);
38 cout<<"Sorted array: \n";
39 printArray(arr, n);
40 return 0;
41}