Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to implement bubble sort algorithm.

Write a program to implement bubble sort algorithm.

Given a integer array ,we have to sort an array in ascending order using bubble sort algorithm.

Example:

input:arr[]={1,5,3,2}
output:1,2,3,5

Logic:

In bubble sort algorithm,it will swap adjacent element repeatedly if that is minimum to other element.

Code-

#include <bits/stdc++.h> 
using namespace std; 
void swap(int *x, int *y) 
{ 
	int temp = *x; 
	*x = *y; 
	*y = temp; 
} 
void bubbleSort(int arr[], int n) 
{ 
	 
	for (int i = 0; i < n-1; i++)	 
	{
	for (int j = 0; j < n-i-1; j++) 
	{
		if (arr[j] > arr[j+1]) 
		{
			swap(&arr[j], &arr[j+1]); 
		}
	}
	}
}
int main() 
{ 
	int arr[] = {4, 3, 2, 1, 22, 11, 9}; 
	int n = sizeof(arr)/sizeof(arr[0]); 
	bubbleSort(arr, n); 
		for (int i = 0; i < n; i++) 
		{
		cout << arr[i] << " "; 
		}
	cout << endl; 

} 


Output:

1 2 3 4 9 11 22 

Time complexity:0(N*N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments