Let's begin!
Bubble Sort is a Sorting Algorithm which has two parts:
- Bubbles up the largest element at the last.
- Keep checking if the list is sorted.
One function will keep bringing the biggest elements at the last of the list and another function will recursively calling it until the list is sorted.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
void print(int*arr, int length = 5) | |
{ | |
for(int i = 0; i < length; i++) | |
{ | |
std::cout<<arr[i]<<" "; | |
} | |
std::cout<<"\n"; | |
} | |
int *bubble(int *arr, int length = 5) | |
{ | |
int i = 0; | |
while (i <= length) | |
{ | |
if(arr[i] > arr[i+1]) | |
{ | |
int temp = arr[i]; | |
arr[i] = arr[i+1]; | |
arr[i+1] = temp; | |
} | |
i+=1; | |
} | |
return arr; | |
} | |
int *bubble_sort(int *arr, int length = 5) | |
{ | |
arr = bubble(arr); | |
for(int i=0 ; i<length; i++) | |
{ | |
if(arr[i] > arr[i+1]) | |
{ | |
bubble_sort(arr); | |
} | |
} | |
return arr; | |
} | |
int main() | |
{ | |
int arr[5] = {3,6,50,2,9}; | |
print(arr); | |
print(bubble_sort(arr)); | |
return 0; | |
} | |
Comments
Post a Comment