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}
1// below we have a simple C program for bubble sort
2#include <stdio.h>
3
4void bubbleSort(int arr[], int n)
5{
6 int i, j, temp, flag=0;
7 for(i = 0; i < n; i++)
8 {
9 for(j = 0; j < n-i-1; j++)
10 {
11 // introducing a flag to monitor swapping
12 if( arr[j] > arr[j+1])
13 {
14 // swap the elements
15 temp = arr[j];
16 arr[j] = arr[j+1];
17 arr[j+1] = temp;
18 // if swapping happens update flag to 1
19 flag = 1;
20 }
21 }
22 // if value of flag is zero after all the iterations of inner loop
23 // then break out
24 if(flag==0)
25 {
26 break;
27 }
28 }
29
30 // print the sorted array
31 printf("Sorted Array: ");
32 for(i = 0; i < n; i++)
33 {
34 printf("%d ", arr[i]);
35 }
36}
37
38int main()
39{
40 int arr[100], i, n, step, temp;
41 // ask user for number of elements to be sorted
42 printf("Enter the number of elements to be sorted: ");
43 scanf("%d", &n);
44 // input elements if the array
45 for(i = 0; i < n; i++)
46 {
47 printf("Enter element no. %d: ", i+1);
48 scanf("%d", &arr[i]);
49 }
50 // call the function bubbleSort
51 bubbleSort(arr, n);
52
53 return 0;
54}