Example 1: bubble sort in java
public static void bubbleSort(int arr[])
{
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < (arr.length - 1 - i); j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Example 2: bubble sort c
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
return 0;
}
Example 3: 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 4: bubble_sort
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter number of element you want to store: ";
cin>>n;
int arr[n],i,j;
cout<<"Enter array values:\n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"After Bubble sort the array is:\n";
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
Example 5: Write a program to sort an array 100,200,20, 75,89.198, 345,56,34,35 using Bubble Sort. The program should be able to display total number of passes used for sorted data in given data set.
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
Example 6: 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;
}