1void bubble_sort( int A[ ], int n ) {
2 int temp;
3 for(int k = 0; k< n-1; k++) {
4 // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations
5
6 for(int i = 0; i < n-k-1; i++) {
7 if(A[ i ] > A[ i+1] ) {
8 // here swapping of positions is being done.
9 temp = A[ i ];
10 A[ i ] = A[ i+1 ];
11 A[ i + 1] = temp;
12 }
13 }
14 }
15}
1public static void bubbleSort(int arr[])
2{
3 for (int i = 0; i < arr.length; i++) //number of passes
4 {
5 //keeps track of positions per pass
6 for (int j = 0; j < (arr.length - 1 - i); j++) //Think you can add a -i to remove uneeded comparisons
7 {
8 //if left value is great than right value
9 if (arr[j] > arr[j + 1])
10 {
11 //swap values
12 int temp = arr[j];
13 arr[j] = arr[j + 1];
14 arr[j + 1] = temp;
15 }
16 }
17 }
18}
1/* Bubble sort code in C++ */
2#include <bits/stdc++.h>
3using namespace std;
4int main (void) {
5 int a[] = {5, 4, 3, 2, 1}, tempArr, i, j;
6 for (i = 0; i < 5; i++) {
7 for (j = i + 1; j < 5; j++) {
8 if (a[j] < a[i]) {
9 tempArr = a[i];
10 a[i] = a[j];
11 a[j] = tempArr;
12 }
13 }
14 }
15 for(i = 0; i < 5; i++) {
16 cout<<a[i]<<"\n";
17 }
18 return 0;
19}
1#include <iostream>
2
3using namespace std;
4
5
6void heapify(int arr[], int n, int i)
7{
8 int largest = i;
9 int l = 2 * i + 1;
10 int r = 2 * i + 2;
11
12
13 if (l < n && arr[l] > arr[largest])
14 largest = l;
15
16
17 if (r < n && arr[r] > arr[largest])
18 largest = r;
19
20
21 if (largest != i) {
22 swap(arr[i], arr[largest]);
23
24
25 heapify(arr, n, largest);
26 }
27}
28
29
30void heapSort(int arr[], int n)
31{
32
33 for (int i = n / 2 - 1; i >= 0; i--)
34 heapify(arr, n, i);
35
36
37 for (int i = n - 1; i > 0; i--) {
38
39 swap(arr[0], arr[i]);
40 heapify(arr, i, 0);
41 }
42}
43
44
45void printArray(int arr[], int n)
46{
47 for (int i = 0; i < n; ++i)
48 cout << arr[i] << " ";
49 cout << "\n";
50}
51
52
53int main()
54{
55 int arr[] = { 12, 11, 13, 5, 6, 7 };
56 int n = sizeof(arr) / sizeof(arr[0]);
57
58 heapSort(arr, n);
59
60 cout << "Sorted array is \n";
61 printArray(arr, n);
62}
1void bubbleSort (int S[ ], int length) {
2 bool isSorted = false;
3 while(!isSorted)
4 {
5 isSorted = true;
6 for(int i = 0; i<length; i++)
7 {
8 if(S[i] > S[i+1])
9 {
10 int temp = S[i];
11 S[i] = S[i+1];
12 S[i+1] = temp;
13 isSorted = false;
14 }
15 }
16 length--;
17}
18}
19
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}