sorting bubble sort code example
Example 1: Bubble sort
class Sort
{
static void bubbleSort(int arr[], int n)
{
if (n == 1)
{
return;
}
for (int i=0; i<n-1; i++)
{
if (arr[i] > arr[i+1])
{
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
bubbleSort(arr, n-1);
}
void display(int arr[])
{
for (int i=0; i<arr.length; ++i)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String[] args)
{
Sort ob = new Sort();
int arr[] = {6, 4, 5, 12, 2, 11, 9};
bubbleSort(arr, arr.length);
ob.display(arr);
}
}
Example 2: bubble sort
#include <iostream>
using namespace std;
void swap(int*,int*);
void bubble_sort(int arr[],int n)
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void display(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cout<<"enter the size of the array:"<<endl;
cin>>n;
int array_of_numbers[n];
cout<<"enter the elements of the array"<<endl;
for(int i=0;i<n;i++)
{
cin>>array_of_numbers[i];
}
cout<<"array as it was entered:"<<endl;
display(array_of_numbers,n);
bubble_sort(array_of_numbers,n);
cout<<"array after bubble sort:"<<endl;
display(array_of_numbers,n);
return 0;
}
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}