bubble sort meaning code example
Example 1: bubble sort code
func Sort(arr []int) []int {
for i := 0; i < len(arr)-1; i++ {
for j := 0; j < len(arr)-i-1; j++ {
if arr[j] > arr[j+1] {
temp := arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
return arr
}
Example 2: c++ buble sort
void bubbleSort(int arr[], int size){
int temp = int();
for ( int i = 0; i < size -1; i ++)
cout << arr[i] << "\t";
cout << endl << endl;
for (int i = 1; i < size; i++ ){
for(int j = 0; j < size - i ; j ++){
if( arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
Example 3: bubble sort algorithm
#include <bits/stdc++.h>
using namespace std;
void bubbleSort(int arr[], int n){
int temp,i,j;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main(){
int arr[] = {1,7,33,9,444,2,6,33,69,77,22,9,3,11,5,2,77,3};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
for(int i=0;i<n;i++){
cout << arr[i] << " ";
}
return 0;
}