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
2void bubbleSort(int arr[], int n){
3 int i, j;
4 for (i = 0; i < n-1; i++)
5
6 for (j = 0; j < n-i-1; j++)
7 if (arr[j] > arr[j+1])
8 swap(&arr[j], &arr[j+1]);
9}
10
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}
1func Sort(arr []int) []int {
2 for i := 0; i < len(arr)-1; i++ {
3 for j := 0; j < len(arr)-i-1; j++ {
4 if arr[j] > arr[j+1] {
5 temp := arr[j]
6 arr[j] = arr[j+1]
7 arr[j+1] = temp
8 }
9 }
10 }
11 return arr
12}